In the following code I have Array.forEach, it performs a synchronous function doSomethingin sequence:
items.forEach(function(item) {
doSomething(item);
});
I need to execute functions ( doSomething) in parallel, use async.jsand 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);
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 the function was doSomethingperformed in sequence.
I tried with async.parallel, but the function doSomethingwas 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);
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 synchronous function doSomethingin parallel with async.js?
Please help me.
source
share