为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

紫衣仙女 2021-06-16 18:10:56
我有一个从一开始就_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);            }        });    }}提前感谢您的任何帮助和建议。
查看完整描述

1 回答

?
守着星空守着你

TA贡献1799条经验 获得超8个赞

正如评论中提到的,请求库不返回承诺,而是使用回调。您可以使用像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。


查看完整回答
反对 回复 2021-06-18
  • 1 回答
  • 0 关注
  • 486 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信