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


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

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?

Array.forEach is meant for computing stuff not waiting, and there is nothing to be gained making computations asynchronous in an event loop (webworkers add multiprocessing, if you need multi-core computation). If you want to wait for multiple tasks to end, use a counter, which you can wrap in a semaphore class.

This is a short asynchronous function to use without requiring third party libs

Array.prototype.each = function (iterator, callback) {
    var iterate = function () {
            if (pointer >= this.length) {
  , this[pointer], iterate, pointer);
        pointer = -1;

It is possible to code even the solution like this for example :

 var loop = function(i, data, callback) {
    if (i < data.length) {
        //TODO("SELECT * FROM Users;", function(res) {
            //data[i].meta = res;
            console.log(i, data[i].title);
            return loop(i+1, data, errors, callback);
    } else {
       return callback(data);

loop(0, [{"title": "hello"}, {"title": "world"}], function(data) {

On the other hand, it is much slower than a "for".

Otherwise, the excellent Async library can do this: