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);
开发者_C百科 },
],
// 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?
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.
精彩评论