在类中使用async await分配属性,但返回null

时间:2019-06-03 19:19:19

标签: javascript class promise async-await

我有一堂课,从一开始_code设置为null,然后向url发出请求以获取结果。

以某种方式分配结果的类的属性代码后,我仍然可以得到null。

我这是怎么了?

class R {
    constructor() {
        this._code = null;
    }

    get code() {
        return this._code;
    }

    set code(value) {
        this._code = value;
    }

    async makingRequests(id) {
        await this.requestToGetCode(id);
        // this gives me null
        console.log(this.code, 'this.code in rquest');
    }

    async requestToGetCode(id) {
        await request(url, async (error, response, body) => {
            if (body !== 'found_no_results') {
                switch (response.statusCode) {
                    case 200:
                        this.code = await JSON.parse(body);
                        // this does give me the proper result though
                        console.log(this.code, 'this.code in requestToGetCode');
                        break;
                    case 404:
                        console.log('page not found');
                        break;
                    default:
                        break;
                }
            } else {
                console.log(body, id);
            }
        });
    }
}

在此先感谢您的帮助和建议。

1 个答案:

答案 0 :(得分:1)

如注释中所述,请求库不返回promise,而是与回调一起使用。您可以使用request-promise之类的库来解决此问题。但是,如果由于某种原因您不想这样做,此答案可能会对您有所帮助。

要能够对请求库使用异步/等待,您需要将调用手动包装在Promise中。

async requestToGetCode(id) {
    await new Promise((resolve, reject) => {
        request(url, (error, response, body) => {
            if (body !== 'found_no_results') {
                switch (response.statusCode) {
                    case 200:
                        this.code = JSON.parse(body);
                        // this does give me the proper result though
                        console.log(this.code, 'this.code in requestToGetCode');
                        resolve();
                        break;
                    case 404:
                        console.log('page not found');
                        reject('Not found');
                        break;
                    default:
                        // Reject all other cases
                        reject('Error');
                        break;
                }
            } else {
                // Reject as we do not receive the correct response
                console.log(body, id);
                reject('Error');
            }
        });
    });
}

本质上,我们在这里创建一个新的Promise,它将为我们完成请求。然后在请求回调中根据结果调用resolvereject