如何与async.js并行执行函数? [英] How to execute functions in parallel with async.js?
问题描述
在下面的代码中,我有 Array.forEach
,它按顺序执行 doSomething
同步函数: / p>
In the following code, I have Array.forEach
, It executes the doSomething
synchronous function in sequence:
items.forEach(function(item) {
doSomething(item);
});
我需要执行函数( doSomething
)并行使用 async.js
并尝试以下操作:
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');
});
但函数 doSomething
是按顺序执行的。
But function doSomething
was executed in sequence.
我曾尝试使用 async.parallel
,但函数 doSomething
再次按顺序执行:
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');
});
如何并行执行 doSomething
同步功能使用 async.js
?
How to execute doSomething
synchronous function in parallel with async.js
?
请帮帮我。
推荐答案
如何与async.js并行执行doSomething同步函数?
How to execute doSomething synchronous function in parallel with async.js?
你不能。 async.js
仅用于异步任务,因此名称(另请参阅 this回答同步行为)。此外,JavaScript无法并行执行代码,因为它具有公平的单线程范式;它只能为下一个事件并行等待。
You cannot. async.js
is made for asynchronous tasks only, hence the name (see also this answer on synchronous behaviour). Also, JavaScript cannot execute code in parallel because of its evented, single-threaded paradigm; it can only "wait" in parallel for the next event.
如果您的同步执行确实存在问题,请尝试将数组拆分为较小的块并将其推迟非阻塞行为的超时(请参阅 JavaScript性能长期运行任务,如何阻止激烈的Javascript循环冻结浏览器),或者考虑WebWorkers进行非常繁重的计算。您可以使用async.js来管理它们。
If you really have problems with your synchronous execution, try splitting up the array in smaller chunks and defer them with timeouts for non-blocking behaviour (see JavaScript Performance Long Running Tasks, How to stop intense Javascript loop from freezing the browser), or consider WebWorkers for really heavy computations. You can use async.js to manage those, then.
这篇关于如何与async.js并行执行函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!