【问题标题】:Can't set properties on child class after async calling constructor of base class. NodeJS v8.2.1异步调用基类的构造函数后,无法在子类上设置属性。 NodeJS v8.2.1
【发布时间】: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 之外的所有属性都是未定义

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

提前谢谢你。

【问题讨论】:

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


【解决方案1】:

我不明白为什么没有设置 this.document 属性。我只看到在异步回调中设置的 this.auth。

您的CSheet 构造函数确实在super() 返回的promise 上设置了documentsomeAnotherProp 属性。 awaiting 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,并且只将普通值传递给构造函数。

【讨论】:

    猜你喜欢
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 2015-12-26
    • 2015-08-18
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多