Is map() in javascript synchronous?

user3815910 picture user3815910 · Jul 8, 2014 · Viewed 32.8k times · Source

Function is :

[1,2,3].map( function (item)
{
  console.log(item);
  //return 'something';
});

My expected behaviour is getting only 1 as output, unless i uncomment the

//return 'something'

But i really get

1
2
3

What am i doing wrong ?

UPDATE:

i am testing that with nodejs.

i really dont understand.

var async = require("async");

[1,2,3].map( function (item)
{
      console.log(item);
      //return 'something';
}); 
async.map([1,2,3], function (item,callback)
    {
        console.log(item);
        //callback(null,true)
    }, function (err,result)
        {
            console.log(result);
        }
);

Both return the same

1
2
3

And i really would like to wait till i get a return or a callback till the next item is executed.

SOLVED

async.mapSeries([1,2,3], function (item,callback)
    {
        console.log(item);
        //callback(null,true)
    }, function (err,result)
        {
            console.log(result);
        }
);

is the way to do it.

Answer

funerr picture funerr · Oct 23, 2015

Yes, map is synchronous.
It's a higher order function, that takes a new function and applies it to the given array.

Some people think that because they give a function as a parameter to map then it 'should' act like an event callback function, but it really doesn't. The map function just applies the function parameter to the array and only after it finishes, it continues execution for the resulting code after the map block.

As to your 'expected behavior' - it just doesn't work like you think ;)