In the following code, I have Array.forEach
, It executes the doSomething
synchronous function in sequence:
items.forEach(function(item) {
doSomething(item);
});
I need to execute functions (doSomething
) in parallel, use async.js
and try the following:
async.each(items, function (item, doneCallback) {
var startDate = new Date();
console.log(item.name().toString() + ' startDate: ' + startDate.toString() + ' - ' + startDate.getMilliseconds().toString());
doSomething(item); //Lazy function for many operations.
var endDate = new Date();
console.log(item.name().toString() + ' endDate' + endDate.toString() + ' - ' + endDate.getMilliseconds().toString());
return doneCallback(null);
}, function (err) {
otherFunction();
console.log('Finished');
});
But function doSomething
was executed in sequence.
I had tried with async.parallel
, but function doSomething
was executed in sequence again:
items.forEach(function (item) {
var func = function (doneCallback) {
var startDate = new Date();
console.log(item.name().toString() + ' startDate: ' + startDate.toString() + ' - ' + startDate.getMilliseconds().toString());
doSomething(item); //Lazy function for many operations.
var endDate = new Date();
console.log(item.name().toString() + ' endDate' + endDate.toString() + ' - ' + endDate.getMilliseconds().toString());
return doneCallback(null);
};
functions.push(func);
});
async.parallel(functions, function (err, results) {
otherFunction();
console.log('Finished');
});
How to execute doSomething
synchronous function in parallel with async.js
?
Please help me.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…