您能否帮助理解在父类的回调中使用 Promise,然后尝试在子类上设置属性时可能出现的问题?
我使用的是nodejs v8.2.1
这是基类的示例:
class CGLBase extends CAuthClient
{
constructor(req, res)
{
return new Promise(resolve => {
super(req, res, (authClient) => {
this.setAuthClient(authClient);
resolve(this);
});
});
}
setAuthClient(authClient)
{
//setting authClient (this.auth will contain property)
}
}
这里是子类的示例:
class СSheet extends CGLBase
{
constructor(document, urlRequest, urlResponse)
{
super(urlRequest, urlResponse);
this.document = document;
this.someAnotherProp = "some property";
//etc..
}
someFunc()
{
//using this.document and this.auth
}
}
之后,我创建 СSheet 实例并尝试设置属性:
var document = { ... }; //here I create object
(async () => {
var docSheet = await new СSheet (document, req, res);
docSheet.someFunc();
console.log(docSheet.auth); //return correct property
console.log(docSheet.document); //return undefined. why...
})();
所以,我不明白为什么没有设置属性this.document。我只看到在异步回调中设置的 this.auth 。所有属性除了 this.auth 都是未定义。
我将非常感谢您的建议或帮助。
提前谢谢您。
最佳答案
I don't understand why property this.document wasn't set. I see only this.auth that was set in the async callback.
您的 CSheet
构造函数确实在 super()
返回的 promise 上设置了 document
和 someAnotherProp
属性。 await
new CSheet
将为您提供解析 Promise 的 CAuthClient
实例,该实例不具有属性。
您可以通过使用来解决这个问题
class СSheet extends CGLBase {
constructor(document, urlRequest, urlResponse) {
return super(urlRequest, urlResponse).then(instance => {
instance.document = document;
instance.someAnotherProp = "some property";
// …
return instance;
});
}
…
}
但是你really absolutely never should do that 。这当然是 CAuthClient
采取异步回调的错误。修复该类及其所有子类,以在静态帮助器方法中异步创建 authClient,并且仅将纯值传递到构造函数中。
关于javascript - 异步调用基类的构造函数后无法在子类上设置属性。 NodeJS v8.2.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45552186/