[英]Javascript how await promise inside extend Error
我目前正在嘗試擴展 javascript 的標准錯誤 class 以解決流程問題,更准確地說,我想在拋出我的 customError 時檢查 FTP 數據。 問題是它從不等待等待 function 在拋出之前完成。 等待的 function 也返回 promise。
就我而言,我的 class 有這個示例代碼,請注意,remoteFs 只是一個自定義模塊,其中包含我用於操作遠程 FTP 數據的函數。
module.exports = class processError extends Error {
constructor(args) {
super(args);
this.name = "customError"
this._folder = "./test/"
this._credentials = {
host: 'my.host.com',
user: 'username',
password: 'passwd123',
}
return (this._errorProcess());
}
async _errorProcess () {
try {
// The function below is basic FTP list and should return a promised true/false if the folder exists or not.
let IsThereFolder = await remoteFs.EntityExist(this._credentials, this._folder)
} catch (err) {
throw new Error("Fatal error in error handler:", err)
}
console.log("Should I create folder ?", IsThereFolder )
return (this);
}
}
我嘗試了幾種方法讓構造函數等待,例如從 init() function 調用 _errorProcess ,它會在從構造函數調用后返回它。 I also tried to put this function out the class scope but nothing seems to work properly, I always end up having the throwing output before receiving my promise.
module.exports = {
EntityExist: function (credentials, toFind) {
var c = new Client();
let entityExist = false;
return new Promise((resolve, reject) => {
console.log("CREDENTIALS ->", credentials)
c.on('ready', function () {
console.log("Connection established");
c.on('error', function (err) {
console.log(err);
reject(err);
})
c.list(toFind, (err, list) => {
if (err) throw err;
for (let i = 0; i < list.length; i++) {
if (list[i].name == toFind) { entityExist = true; }
}
c.on('end', () => { resolve(entityExist); })
c.end();
});
});
console.log("Before connect")
c.connect(credentials);
})
}
};
這是我執行此操作得到的實際 output:
CREDENTIALS -> { host: 'my.host.com',
user: 'username',
password: 'passwd123' }
Before connect
C:\path_to_project\includes\file.js:62
throw new handleError("Testing custom error: " + err); break;
^
[object Promise]
npm ERR! code ELIFECYCLE
npm ERR! errno 1
(...)
如您所見,它不會等待 promise 回來,甚至沒有到達 EntityExist function 上的“已建立連接”日志(請不要認為這個 ZC1C425268E68385D1AB5074F 在另一個環境中工作正常)。
實際上,我什至不知道是否可以直接從構造函數執行此類操作。 我希望上下文足夠清楚,感謝您的時間!
await 運算符用於等待 Promise。 它只能在異步 function 內部使用。
這意味着您不能在全局 scope 或 class 構造函數中使用。
使用 promise 的構造函數是一種不好的做法,因為您也將無法獲得 class (鏈接到另一個 stackoverflow 答案) 。
從技術上講,您可以從構造函數返回 Promise ,但這不是他的目的。
對於您的情況,您可以在調用投擲之前使用 function,這並不漂亮,但它可以完成工作。
作為:
async generateAsyncError(asyncFn) {
await asyncFn();
throw new Error();
}
在這里,您可以在拋出錯誤之前使用異步。 但請記住,在異步 function 完成之前不會拋出錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.