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

标签 javascript node.js express asynchronous recursion

我有一个名为 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/

相关文章:

node.js - 快速静态中间件和子目录的问题

javascript - 表单不使用 Ajax,直接发布到 PHP

javascript - 无论如何,有没有办法使实例的名称等于构造函数而不用 new ?

javascript - MongoDB 拒绝大容量 (10000) 插入/写入连接

node.js - LocomotiveJS 服务器端口更改

javascript - createRecord 将空 req.body 发送到我的 express.js 服务器后,Ember.js save()

JavaScript/Ajax/Json : Sending objects and arrays

Javascript 检查互联网连接,如果没有则在 div 中写入一行

node.js - 如何将mean.js部署到生产环境?

javascript - 如何在不重新加载或重新呈现页面的情况下将 JSON 从 node.js 后端返回到前端?