0

I have below function which fetches data in parallel. Once the fetching data is done the result will be available via 'results' variable in the callback function. I needs to parameterize instead of hard coding 'products', 'images' etc. I need to be able to pass an array. (i.e I need to say var fetchInParallel = function (id, res, names) ) where names = ['products', 'images']

How would I do that? I tried using forEach with no luck.

var fetchInParallel = function (id, res) {

async.parallel(
    [
        function (callback) {
            commonService.findById('products', id, function (result) {
                callback(false, result);
            })
        },

        function (callback) {
            commonService.findById('images', id, function (result) {
                callback(false, result);
            })
        }

    ],

    function (err, results) {
        // handle errors code

        var products = results[0];
        var volatile = results[1];

        var target = stitch(products,images);

        res.send(target)
    }
);
}
Community
  • 1
  • 1
ravindrab
  • 2,712
  • 5
  • 27
  • 37
  • How would your result callback look like if it had to deal with dynamic `names`, instead of hardcoded products and volatile images? – Bergi Feb 26 '15 at 17:58
  • in fact they are dynamic names, the `stich` function will iterate the `results` and stitch the final result. – ravindrab Feb 26 '15 at 18:24

2 Answers2

3

You're looking for the map function:

function fetchInParallel(id, names, res) {
    async.map(names, function(name, callback) {
        commonService.findById(name, id, function (result) {
            callback(null, result);
        });
    }, function (err, results) {
        if (err)
            … // handle error code
        var target = stitch(results); // combine names with results
        res.send(target)
    });
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
2

you can use async.map instead of parallel like this;

var fetchInParallel = function (id, res,names) {
    async.map(names,
        function (name,callback) {
            commonService.findById(name, id, function (result) {
                callback(null, result);
            })
        },

        function (err, results) {

        }
    );
}
Safi
  • 1,112
  • 7
  • 9