I have a question regarding the native Array.forEach
implementation of JavaScript: Does it behave asynchronously?
For example, if I call:
[many many elements].forEach(function () {lots of work to do})
Will this be non-blocking?
I have a question regarding the native Array.forEach
implementation of JavaScript: Does it behave asynchronously?
For example, if I call:
[many many elements].forEach(function () {lots of work to do})
Will this be non-blocking?
No, it is blocking. Have a look at the specification of the algorithm.
However a maybe easier to understand implementation is given on MDN:
If you have to execute a lot of code for each element, you should consider to use a different approach:
and then call it with:
This would be non-blocking then. The example is taken from High Performance JavaScript.
Another option might be web workers.
Here is a small example you can run to test it:
It will produce something like this(if it takes too less/much time, increase/decrease the number of iterations):
This is a short asynchronous function to use without requiring third party libs
It is possible to code even the solution like this for example :
On the other hand, it is much slower than a "for".
Otherwise, the excellent Async library can do this: https://caolan.github.io/async/docs.html#each
There is a package on npm for easy asynchronous for each loops.
Also another variation forAllAsync
If you need an asynchronous-friendly version of Array.forEach and similar, they're available in the Node.js 'async' module: http://github.com/caolan/async ...as a bonus this module also works in the browser.