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

我有一个从一开始就_code设置为的类,null然后向 an 发出请求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);

            }

        });

    }

}

提前感谢您的任何帮助和建议。


紫衣仙女
浏览 487回答 1
1回答

守着星空守着你

正如评论中提到的,请求库不返回承诺,而是使用回调。您可以使用像request-promise这样的库来解决这个问题。但是,如果您出于某种原因不想这样做,则此答案可能会对您有所帮助。为了能够将 async/await 与 Request 库一起使用,您需要手动将调用包装在 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,它将为我们完成请求。在请求回调中,我们然后根据结果调用resolve或reject。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript