async调用基类的构造函数之后,无法在子类上设置属性。 NodeJS v8.2.1

你可以请帮忙了解什么可能是错误,而在父类的callback中使用承诺,然后尝试设置子类的属性?

我正在使用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 } } 

之后,我创buildС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... })(); 

所以,我不明白为什么财产这个文件没有设置。 我只看到在asynchronouscallback中设置的this.auth除了this.auth之外的所有属性都是未定义的

我将非常感谢您的build议或帮助。

先谢谢你。

我不明白为什么财产这个文件没有设置。 我只看到在asynchronouscallback中设置的this.auth。

你的CSheet构造函数确实在super()返回的promise上设置了documentsomeAnotherProp属性。 await new CSheet给你CAuthClient实例,该承诺解决了,并没有属性。

可以通过使用

 class СSheet extends CGLBase { constructor(document, urlRequest, urlResponse) { return super(urlRequest, urlResponse).then(instance => { instance.document = document; instance.someAnotherProp = "some property"; // … return instance; }); } … } 

但你真的绝对不应该这样做 。 这当然是CAuthClient采取asynchronouscallback的错误。 修正该类及其所有子类在静态帮助方法中执行authClient的asynchronous创build,并仅将简单值传递给构造函数。