gpt4 book ai didi

javascript - NodeJS 异步/等待 + 快速请求递归

转载 作者:行者123 更新时间:2023-12-03 03:33:18 25 4
gpt4 key购买 nike

我有一个名为 GetAllData() 的函数,它调用 GetPurchaseData,该函数会递归调用自身,直到加载所有数据。在

async function GetAllData(){
console.log("starting loading purchase data");
await GetPurchaseData();
console.log("purchase data loaded")
}

async function GetPurchaseData(){
return new Promise(async function (resolve,reject){
var Headers = {
....
}
await request({url: xxx, headers: Headers },async function(error, response, body) {
var tmp = JSON.parse(body)
_.forEach(tmp.Purchases, p => purchaseData.push(p));

if (response.headers.pagination){
return await GetPurchasePaginatedData()
}
else{
console.log("done loading....")
return resolve("done")
}
});
})
}

Node JS 打印以下输出:

starting loading purchase data 
done loading....

但它永远不会返回到 GetAllData 进行打印

purchase data loaded

它看起来几乎陷入了功能困境,但我的观点是,不知何故,“returnsolve("done")”行并没有回到最初的调用以实际将 Promise 标记为完成。

>

最佳答案

避免 async/await Promise constructor antipattern (另请参阅 here ),并避免将 async 函数作为常规回调传递 - 您需要 use the Promise constructor to promisify an existing callback API !

async function GetPurchaseData() {
var headers = {…};
var promise = new Promise((resolve,reject) => { // not async!
request({url: xxx, headers}, (error, response, body) => { // not async!
if (error) reject(error);
else resolve({response, body});
});
}); // that's it!

var {response, body} = await promise;
for (var p of JSON.parse(body).Purchases)
purchaseData.push(p));

if (response.headers.pagination) {
return GetPurchasePaginatedData()
} else {
console.log("done loading....")
return "done";
}
}

关于javascript - NodeJS 异步/等待 + 快速请求递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45987513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com