1 回答

TA貢獻(xiàn)1799條經(jīng)驗 獲得超8個贊
正如評論中提到的,請求庫不返回承諾,而是使用回調(diào)。您可以使用像request-promise這樣的庫來解決這個問題。但是,如果您出于某種原因不想這樣做,則此答案可能會對您有所幫助。
為了能夠?qū)?async/await 與 Request 庫一起使用,您需要手動將調(diào)用包裝在 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');
}
});
});
}
本質(zhì)上,我們在這里創(chuàng)建了一個新的 Promise,它將為我們完成請求。在請求回調(diào)中,我們?nèi)缓蟾鶕?jù)結(jié)果調(diào)用resolve或reject。
添加回答
舉報