A
A
aleksandrvin2013-04-06 15:22:56
JavaScript
aleksandrvin, 2013-04-06 15:22:56

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

5 answer(s)
S
Sergey, 2013-04-07
@aleksandrvin

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/

Y
Yuri Shikanov, 2013-04-06
@dizballanze

The async module is here to help. Namely, the map method .

L
lacki, 2013-04-06
@lacki

You can do it like this: github.com/caolan/async#eachseriesarr-iterator-callback

A
aleksandrvin, 2013-04-06
@aleksandrvin

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 */ ???
});

And the parallelism or seriality of the operation of map or eachSeries does not play a role here.

A
aleksandrvin, 2013-04-06
@aleksandrvin

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 question

Ask a Question

731 491 924 answers to any question