简体   繁体   English

在构造函数中的Promise中设置类属性

[英]Setting class properties in a promise in a constructor

Question is quite simple, in this code here 问题很简单,在此代码中

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';
                }
            });
        }
    }
}

I'm trying to set a property of the class as the result of a callback function. 我正在尝试将类的属性设置为回调函数的结果。 However, when executing this code 但是,执行此代码时

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

The value returned is undefined, which seems to indicate the constructor function finishes before the callback is executed. 返回的值是不确定的,这似乎表明构造函数在执行回调之前完成。 Shouldn't the constructor block until the callback is complete? 构造函数是否应该在回调完成之前阻塞? Is there a better way to do this? 有一个更好的方法吗?

It's asynchronous , so it won't be done yet when new Identifier finishes. 它是异步的 ,因此在new Identifier完成时还不会完成。

Instead, offer a completion promise, probably from a setter rather than the constructor: 取而代之的是提供一个完成承诺,可能是一个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...*/);

Alternately, if providing the ID in the constructor is important: 或者,如果在构造函数中提供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...*/);

But you do need to check that that promise has resolved before expecting things to be complete. 但是您确实需要在期望完成之前检查该诺言是否已解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM