Node.js Api 在异步循环中调用 [英] Node.js Api calls in an Async loop

查看:50
本文介绍了Node.js Api 在异步循环中调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难进行多次 api 调用并在正确的位置获取返回的结果.这就是我想要实现的目标:嵌套的两个循环.外循环遍历一个复杂的 json 对象,并将一些对象的值放置在一个数组调用框中.内部循环调用 api 并将返回的结果放入名为 bag 的数组中.所以我有装满数据的盒子和袋子.当循环和 api 调用都结束时,我希望能够访问 box 和 bag 中的数据并对其进行处理.我只是不确定在执行的同一点访问两个数组的最佳方法.到目前为止,这是我所拥有的,但当然 bag 和 box 是空的,因为它们在所有循环和 api 调用结束之前被调用.

I'm having difficulty making multiple api calls and getting the returned results in the right place. This what I'm trying to achieve: Two loops, nested. The outer loop loops over a complex json object and places some object's values in an array call box. The inner loop calls the api and the places the returned results in an array named bag. So I have box and bag full of data. When both loops and api calls end, I would like to have access to the data in both box and bag and do stuff with it. I'm just not sure of the best way to go have access to both arrays at the same point in execution. This is what I have so far, but of course bag and box are empty because they get called before all the loops and api calls end.

var data = {}//a json object with data;
var bag = [];
var box = [];

async.forEach(data.item, function(item, callback){

    async.forEach(item.name, function(name, callback){

        callApi(item.name, function(obj){

           bag.push(obj);
        });

        callback();

    }

   box.push(item);
   callback();

});


function callApi(name, callback){

    asyncApiCall(url+name, function(err, result){

        callback(result);       
    });

}

//when all loops and api requests are done
//do stuff with contents of box and bag here;
console.log(bag, box);

推荐答案

您可以使用计数器来确保所有异步调用都已返回,然后调用回调.一个例子:

You can use a counter to ensure all async calls have returned and then call a callback. An example:

function performAsyncOperation(data, onCompletion) {
    var bag = [];
    var box = [];
    var count  = 0;

    async.forEach(data.item, function(item, callback){
        async.forEach(item.name, function(name, callback){
            count += 1;
            callApi(item.name, function(obj){
               bag.push(obj);
               count -= 1;
               if (count == 0) {
                   onCompletion(null, { bag:bag, box:box });
               }
            });
            callback();
        }
       box.push(item);
       callback();
    });
}

countonCompletion 是上面的重要部分.

count and onCompletion are the important parts above.

这篇关于Node.js Api 在异步循环中调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆