【问题标题】:Setting class properties in a promise in a constructor在构造函数的 Promise 中设置类属性
【发布时间】:2017-05-15 20:15:22
【问题描述】:

问题很简单,就在这段代码里

class Identifier {
    constructor(id) {
        if (/^[0-9]*$/.test(id)) {
            database.exists('users', {userid: id}).then(exists => {
                if (exists) {
                    this.id = id;
                } else {
                    throw 'id_not_exist';
                }
            });
        }
    }
}

我正在尝试将类的属性设置为回调函数的结果。但是,当执行此代码时

var ident = new Identifier(1);
console.log(ident.id);

返回的值是未定义的,这似乎表明构造函数在回调执行之前完成。构造函数不应该在回调完成之前阻塞吗?有没有更好的方法来做到这一点?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    它是异步的,所以当new Identifier 完成时它还不会完成。

    相反,提供完成承诺,可能来自 setter 而不是构造函数:

    class Identifier {
        setId(id) {
            if (/^[0-9]*$/.test(id)) {
                return database.exists('users', {userid: id}).then(exists => {
                    if (exists) {
                        this.id = id;
                        resolve(this);
                    } else {
                        throw 'id_not_exist';
                    }
                });
            } else {
                return Promise.resolve(this); // Assuming no ID is okay
            }
        }
    }
    
    let ident = new Identifier();
    ident.setId(1)
        .then(_ => /*...it worked...*/)
        .catch(_ => /*...it failed...*/);
    

    或者,如果在构造函数中提供 ID 很重要:

    class Identifier {
        constructor(id) {
            if (/^[0-9]*$/.test(id)) {
                this.idPromise = database.exists('users', {userid: id}).then(exists => {
                    if (exists) {
                        this.id = id;
                        resolve(this);
                    } else {
                        throw 'id_not_exist';
                    }
                });
            } else {
                this.idPromise = Promise.resolve(this); // Assuming no ID is okay
            }
        }
    }
    
    let ident = new Identifier(1);
    ident.idPromise
        .then(_ => /*...it worked...*/)
        .catch(_ => /*...it failed...*/);
    

    但是在期望事情完成之前,您确实需要检查该承诺是否已解决。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多