Answer the question
In order to leave comments, you need to log in
Calling an asynchronous function from a functional map in JavaScript, how?
There is an array of objects. I would like to map for it by making an HTTP request for each object and returning a new response object.
How to do this if the http module from Node.js is used for HTTP requests, which makes the call asynchronously?
Answer the question
In order to leave comments, you need to log in
If you master the article, the question will disappear blog.jcoglan.com/2013/03/30/callbacks-are-imperative-promises-are-functional-nodes-biggest-missed-opportunity/
You can do it like this: github.com/caolan/async#eachseriesarr-iterator-callback
It doesn't look like it looks like this:
inObjs.map(function /*ААА*/ (o) {
var req = http.request(options, function (res) {
var data = "";
res.on('data', function (chunk) { data += chunk; };
res.on('end', function () { /* Теперь надо объект data вернуть из лямбда-функции ААА */ ??? });
});
res.write(JSON.stringify(o));
res.end();
return /* Здесь надо дождаться того объекта data и вернуть его обратно в map */ ???
});
Here's what happened in the end:
/**
* Event-style map function with fun(e, consumer) as an element
* transformation function that does not return modified object
* but produce it to the ''consumer'' function instead.
*
* Result of the evmap-transformed objects will be transfered in
* the ''callback'' call eventually.
*
* Main use is for maps with asynchronous transformation functions!
*/
function evmap(list, fun, callback) {
function evmap(acc, list, fun) {
if (list && 0 < list.length) {
fun(list.shift(),
function (result) {
acc.unshift(result);
evmap(acc, list, fun);
});
}
else {
callback(acc.reverse());
}
}
evmap([], list, fun);
}
//// unit tests
exports.evmap_array = {
'list': function (test) {
evmap([1,2,3],
function (e, c) { c(e + 10); },
function (result) {
test.deepEqual(result, [11, 12, 13]);
test.done();
});
}
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question