Search code examples
javascriptnode.jsasynchronouscontrol-flowasync.js

Control flow: Run two asynchronous array maps


I have two functions that are asynchronous – they accept a function as a parameter which it called when it is done (callback).

function a(item, cb) {
  someAsyncOperation(function () {
    cb(item)
  })
}

function b(item, cb) {
  someAsyncOperation(function () {
    cb(item)
  })
}

I have an array. I need to run these functions, using Array.prototype.map, on this array two times. When both maps are done, I would like to have a callback which is invoked with two parameters: an error and the mapped array.

What sort of control flow do I need to achieve this? Something in the async library I'm guessing.

In pseudo-ish code:

var example = [1, 2, 3]

async.series([
  function () { example.map(a) },
  function () { example.map(b) }
], function (error, mappedExample) {

})

Solution

  • You can definitely use the async library for this sort of thing, but in this case, you can handle it yourself by simply chaining your functions together:

    var items = ["a", "b", "c", "d" ],
        foo = function (array, cb) {
            "use strict";
            array = array.map(function (element) {
                return "foo-" + element;
            });
    
            cb(array);
        },
        baz = function (array) {
            "use strict";
            array = array.map(function (element) {
                return "baz-" + element;
            });
    
            console.log(array);
        };
    
    foo(items, baz);
    

    Results in:

    [ 'baz-foo-a', 'baz-foo-b', 'baz-foo-c', 'baz-foo-d' ]
    

    If your functions are particularly complex or you do this sort of thing often, then async can definitely be of help; however, there is no reason why can't do it on your own. (You would need to add error handling of course)