4

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 this:

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 isn't called. And so I can't say if all parallel calls are done.

What am I missing here?

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks, i tried yours and thanks to your last sentence i modified it like: callItems.push(makeCallbackFunc(obj, o.title, o.url)); that seemed to work. but now i have the impression that the functions arent called parallel ?
they are parallel, that was just due to some other things

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.