22

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.

user3815910
  • 259
  • 1
  • 2
  • 6
  • 4
    Why is that your "expected behaviour" ? – Alnitak Jul 08 '14 at 10:39
  • Which browser you are trying this ? for google chrome I am getting the result as expected in both of the cases. – robieee Jul 08 '14 at 10:44
  • Note : map calls a provided callback function once for each element in an array. This is What i got in Google chrome debugger : [1,2,3].map( function (item) { console.log(item); //return 'something'; }) 1 VM63:4 2 VM63:4 3 VM63:4 [undefined, undefined, undefined] [1,2,3].map( function (item) { console.log(item); return 'something'; }) 1 VM66:4 2 VM66:4 3 VM66:4 ["something", "something", "something"] – robieee Jul 08 '14 at 10:51

2 Answers2

79

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 ;)

funerr
  • 7,212
  • 14
  • 81
  • 129
2

"The map() method creates a new array with the results of calling a provided function on every element in this array."

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

The callback is called for each item, your logic is executed and the return value is set as an item in the new array.

Or Barmatz
  • 307
  • 3
  • 8