JavaScript, Node.js: is Array.forEach asynchronous?


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?

12/29/2014 10:36:53 AM

Accepted Answer

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 (!Array.prototype.forEach)
  Array.prototype.forEach = function(fun /*, thisp */)
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
      if (i in t), t[i], i, t);

If you have to execute a lot of code for each element, you should consider to use a different approach:

function processArray(items, process) {
    var todo = items.concat();

    setTimeout(function() {
        if(todo.length > 0) {
            setTimeout(arguments.callee, 25);
    }, 25);

and then call it with:

processArray([many many elements], function () {lots of work to do});

This would be non-blocking then. The example is taken from High Performance JavaScript.

Another option might be web workers.

4/10/2019 12:09:52 AM

If you need an asynchronous-friendly version of Array.forEach and similar, they're available in the Node.js 'async' module: a bonus this module also works in the browser.

async.each(openFiles, saveFile, function(err){
    // if any of the saves produced an error, err would equal that error

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow