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)
    }
);
}
2
  • How would your result callback look like if it had to deal with dynamic names, instead of hardcoded products and volatile images? Commented Feb 26, 2015 at 17:58
  • in fact they are dynamic names, the stich function will iterate the results and stitch the final result. Commented Feb 26, 2015 at 18:24

2 Answers 2

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)
    });
}
Sign up to request clarification or add additional context in comments.

Comments

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) {

        }
    );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.