1

I am coding in node.js for 6 months. I have read about concept of asynchronous coding, event loops and callbacks and so on. I know " asynchronous code will never execute while the synchronous code stack is executing. This is the meaning of node.js being single-threaded". But here is one example

var a = [4, 5, 6, 7];
var results = [];

a.forEach(function(result){
  results.push(result + 1);
});

console.log(results);

As far as I understand, argument to a function forEach is callback which is called later after the synchronous block finishes executing. That means I expect the result will be

[]

but it is infact

[5, 6 ,7, 8]

Why is this happening? Is forEach synchronous? Or I am missing something? In my understanding,

console.log(results)

Will be executed before data is pushed into it.

  • 2
    Just because something takes a callback does not mean it's asynchronous. – Sunil D. Mar 23 '15 at 09:38
  • 2
    @SunilD. that means forEach is synchronous. Hmm seems confusing for beginners. Messed up with callbacks, event loop and asynchronous code. How can we know in advance that the method we are calling is asynchronous? –  Mar 23 '15 at 09:48

2 Answers2

3

The callback that you pass to Array.prototype.forEach() is synchronous. Therefore, it is blocking the execution thread until it finishes applying the function to all the members of the array.

I've also managed to find some interesting reads if you want to further investigate the asynchronous nature of JavaScript:

Community
  • 1
  • 1
vladzam
  • 5,462
  • 6
  • 30
  • 36
1

certains functions are synchronous, others asynchronus. In fact, the Array.forEach method and all basic functions are synchronous. If you want manipulate array asynchronously, you have two options : call function in your forEach but you don't know when it's finished or, use async library.

First method :

var a = [4, 5, 6, 7];
var results = [];

a.forEach(function(result){
  (function(i){
    results.push(i);
  }(result+1));
});

console.log(results);

With async.js :

var async = require('async');
var a = [4, 5, 6, 7];
var results = [];

async.eachSeries(a, function(result, done) {
  results.push(result+1);
  done();
}, function () {
  console.log('forEach finished');
});
console.log(results);
throrin19
  • 17,796
  • 4
  • 32
  • 52