OneCompiler

[NodeJS] async.parallel is not waiting for the parallel functions with API calls to complete their execution before main callback gets called in case of an error in any of these parallel functions

I'm facing this issue with async.parallel where, if any one of these parallel functions throws an error, the optional callback is getting executed without waiting for the API call completion and hence resulting in inaccurate results. I want the execution to wait till all the parallel functions are executed. For example, f2 and f4 are not giving accurate results in the below code. Is there any other async function I can use for my usecase?

async.parallel({
    f1: function(callback) {
        //code
    },
    f2: function(callback) {
        //API call
        callback(null, value);
    },
    f3: function(callback) {
        //code
    },
    f4: function(callback) {
        //API call
        callback(null, value);
    }
    .....
}, function(err, results) {
//code
});

1 Answer

3 years ago by

Use reflectAll which lets all the functions to execute.

async.parallel(async.reflectAll({
    f1: function(callback) {
        //code
    },
    f2: function(callback) {
        //API call
        callback(null, value);
    },
    f3: function(callback) {
        //code
    },
    f4: function(callback) {
        //API call
        callback(null, value);
    }
    .....
}, function(err, results) {
//code
}));
3 years ago by coder