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

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

问题描述

我无法进行多次api呼叫,并在正确的位置取得回传结果。这是我想要实现:两个循环,嵌套。外部循环遍历复杂的json对象,并将一些对象的值放置在数组调用框中。内部循环调用api并将返回的结果放置在名为bag的数组中。所以我有盒子和袋子的数据。当两个循环和api调用结束时,我想有权访问盒子和包中的数据,并做它的东西。我只是不知道最好的方法去访问两个数组在同一个执行点。这是我到目前为止,但是当然包和盒子是空的,因为他们在所有循环和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();
    });
}

code> onCompletion 是上面的重要部分。

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

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