【发布时间】:2014-03-11 18:28:20
【问题描述】:
在下面的代码中,我有Array.forEach,它依次执行doSomething同步函数:
items.forEach(function(item) {
doSomething(item);
});
我需要并行执行函数 (doSomething),使用 async.js 并尝试以下操作:
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');
});
但是函数doSomething是按顺序执行的。
我曾尝试使用async.parallel,但函数doSomething 再次按顺序执行:
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');
});
如何与async.js并行执行doSomething同步函数?
请帮帮我。
【问题讨论】:
标签: javascript async.js