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.
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.
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.
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.
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.
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 ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With