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上设置了document
和someAnotherProp
属性。 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,并仅将简单值传递给构造函数。
- 即使在捕获之后,Node.js仍然处于未处理状态
- 尝试/ catchasynchronous/等待块
- 使用asynchronous时使用babel意外的令牌
- validation使用Mocha / Chai和asynchronous/等待引发exception
- 如何在Heroku上启用ES2017function来运行Node.js应用程序?
- 如何asynchronous/等待在我的代码不起作用?
- Intellij Idea警告 – 用aysnc / await“返回的Promise被忽略”
- 我如何在JavaScript中使用asynchronous生成器?
- Node.js最佳实践exception处理 – asynchronous/等待之后