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。
添加回答
举报