javascript - 异步调用基类的构造函数后无法在子类上设置属性。 NodeJS v8.2.1

标签 javascript node.js callback async-await es6-promise

您能否帮助理解在父类的回调中使用 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 上设置了 documentsomeAnotherProp 属性。 awaitnew 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/

相关文章:

javascript - jquery 动态可折叠列表不起作用; jsfiddle 示例

javascript - MutationObserver 和当前/计算的 CSS 样式

javascript - node.js mysql insert id - 如何在插入查询之外公开插入 id?

javascript - 如何从导出为模块的请求中获取回调函数的返回值

c++ - 通过代码触发回调时抑制 GTK 信号

javascript - 闭包和回调

javascript - 获取未点击的 div 的数据属性

javascript - 此代码是否需要在 document.ready 中?

javascript - nodejs 的 View 引擎 Handlebar 在 Hapijs 上的 Angular 代码

node.js - 想要在库存和类别模型(mongodb)中的 sails js 中执行联接查询