passing arrays of functions to async parallel

2019-05-05 02:00发布

i have to pass an array of functions to the async.js module for node.js.
the normal way from the docs would be:

async.parallel([
    function(callback){
        setTimeout(function(){
            callback(null, 'one');
        }, 200);
    },
    function(callback){
        setTimeout(function(){
            callback(null, 'two');
        }, 100);
    },
],
// optional callback
function(err, results){
});

i tried like that:

            for(var i = 0; i < jsonData.length; i++)
            {
                ...
                o.url = serviceurl;
                o.title = jsonData[i];
                var ff = function(callback){
                    obj.loadService(o.title,o.url,callback);
                }
               callItems.push(ff(function(){return true;}));
            }

            async.parallel(
            callItems,
                // optional callback
                function(err, results){
                    console.log('all calls called without any errors');
                });

that runs through but the main callback isnt called.
and so i cant say if all parallel calls are done.

what am i missing here?

1条回答
Emotional °昔
2楼-- · 2019-05-05 02:54

It looks like the closures are improperly formed in the for loop. Try an external function that returns the value you're currently assigning to ff. Example:

for(var i = 0; i < jsonData.length; i++)
{
    ...
    o.url = serviceurl;
    o.title = jsonData[i];
    var ff = makeCallbackFunc(obj, o.title, o.url);
    callItems.push(ff(function () {return true;}));
}

function makeCallbackFunc(obj, title, url) {
    return function (callback) {
      obj.loadService(title, url, callback);
    };
}

I'm a bit confused by what you are adding to callitems - namely the result of calling ff with the function parameter - it won't be a callback, it will execute right away.

查看更多
登录 后发表回答