YES, map function is asynchronous and is part of ECMAScript.
A Array. map() is a very useful function but, unfortunately, it only works with synchronous functions. A simple workaround for using async map functions is to use Promose.
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.
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.
JavaScript is also a functional programming language. What you have here is a «higher order function», a function which takes a function as a parameter. Higher order functions are synchronous (but see note below).
Sources:
map()
is a typical example of a higher order function. It takes a function and applies it to all elements of an array. The definition sounds very «functional». This function is also not provided by Node. It is documented by MDN Array.prototype.map() and specified by ECMAScript 5.1.
To answer your question: Yes, doSomething(nodeIDs)
is called after all elements have been applied.
setTimeout()
is not a higher order function even if it takes a function as a parameter because setTimeout()
is not really purely functional because it uses time. Pure functionality is timeless. For example the result of map()
doesn't depend on time. And that's what this question is really about. If something doesn't depend on time you execute it synchronously. Problem solved.
Thanks to Simon for challenging the definition of the higher order function in JavaScript.
Yes, .map
is synchronous. "Callback" does not imply "asynchronous".
import the async
module to have an asynchronous 'map
' method
var async = require('async');
var arr = ['1','2'];
async.map(arr, getInfo, function (e, r) {
console.log(r);
});
function getInfo(name, callback) {
setTimeout(function() {
callback(null, name + 'new');
}, 1000);
}
This function is synchronous - otherwise it couldn't return the result of the map operation.
Any callbacks that might take longer time (mainly due to IO) are asynchronous in nodejs - unless the method is explicitely marked as being synchronous (such as fs.readFileSync
- but that doesn't use a callback). You probably confused that somehow.
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