Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is map() in javascript synchronous?

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.

like image 519
user3815910 Avatar asked Jul 08 '14 10:07

user3815910


People also ask

Is JavaScript map function asynchronous?

The map functionAn async version needs to do two things. First, it needs to map every item to a Promise with the new value, which is what adding async before the function does. And second, it needs to wait for all the Promises then collect the results in an Array.

Does map support async?

map() is synchronous and does not return a promise. You can't send an asynchronous operation to a function, like map , which expects a synchronous one, and expect it to work.

Are functions in JavaScript synchronous?

Spoiler: at its base, JavaScript is a synchronous, blocking, single-threaded language. That just means that only one operation can be in progress at a time.

What does map () do JS?

Definition and Usage. map() creates a new array from calling a function for every array element. map() calls a function once for each element in an array. map() does not execute the function for empty elements.


1 Answers

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

like image 69
funerr Avatar answered Oct 01 '22 15:10

funerr