【发布时间】:2018-01-15 01:42:36
【问题描述】:
您能否帮助了解在父类的回调中使用承诺然后尝试在子类上设置属性时会出现什么问题?
我正在使用 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 之外的所有属性都是未定义。
我将非常感谢您的建议或帮助。
提前谢谢你。
【问题讨论】:
-
this在 ES6 构造函数中不可用,直到 调用super。当你的回调箭头函数被定义时,this仍然是undefined。另外,我不确定为什么需要创建异步构造函数。似乎这会更好地实现为异步静态工厂方法。 -
构造函数应该从什么时候返回承诺?
-
拥有异步构造函数通常是不好的做法。看到这个答案:stackoverflow.com/questions/43431550/…
标签: javascript node.js callback async-await es6-promise