In the following code, I have Array.forEach
, It executes the doSomething
synchronous function in sequence:
items.forEach(function(i
How to execute doSomething synchronous function in parallel with async.js?
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.
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.
Unfortunately Javascript is a single threaded language. However, HTML5 aims to improve this by adding Web Workers, which allows real OS-level threads to be spawned. If you are able to leverage HTML5 then this may work for you. You would be able to spawn a Web Worker for each item then wait until all threads are complete (joined).
You can only run those funcs in order (maybe this is what you need), for this use eachSeries function instead of each
. Here is a short documentation for eachSeries
:
The same as each only the iterator is applied to each item in the array in series. The next iterator is only called once the current one has completed processing. This means the iterator functions will complete in order.
Expression synchronous function in parallel
- has no sence actually. Parallel means async execution.
If you can refactor doSomething insto an async function you can use the async.parallel function to start running both functions and wait untill both of them call their callbacks.