Skip to content Skip to sidebar Skip to footer

Join All Async Calls To Return Some Result

What will be the performant solution for this problem where I want to make some async calls, wait in last until all the calls are completed, then return the result. function parseA

Solution 1:

In JavaScript multiple asynchronous operations can be handled by using all method on the Promise object. This does not require the use of libraries.

Promise.all returns a Promise and takes an iterable containing multiple Promises that require resolution. Once all Promises in the iterable have resolved the Promise returned by calling Promise.all resolves. If any Promise in the iterable rejects, the Promise returned by Promise.all immediately rejects.

Promise.all resolves with an iterable of all the resolution values of the Promises given to it. Promise.all rejects with the value of the Promise given in the iterable that rejected.

Taking your example, you would use Promise.all like this:

function parseAndMatch(arg1, arg2){
  return Promise.all([
    asyncCall1(arg1, arg2),
    asyncCall2(arg1, arg2),
  ]);
}

parseAndMatch()
  .then(doSomethingElse)
  .catch(handleRejection);

Further reading

Solution 2:

On the basis of @wing answer's I solved this problem using native Promise and npm deasync library. But I'm not sure how efficient and performant it is.

functionparseAndMatch(callback) {
  returnPromise.all([
      newPromise(function(resolve, reject) {
            var sum = 1;
            for (var i = 0; i < 10000; i++) {
                sum++;
            }
            returnresolve(sum);
      }),
      newPromise(function(resolve, reject) {
            var sum = 1;
            for (var i = 0; i < 90000; i++) {
                sum++;
            }
            returnresolve(sum);
      }),
  ]);
}

functionjoinAndReturn(){
    var done = false;
    var result;
    parseAndMatch().then((results) => {
        result = results[0] + results[1];
        done = true;
    });
    deasync.loopWhile(function(){return !done;});
    return result;
}

console.log(joinAndReturn());//100002

Solution 3:

If asyncCall1 and asyncCall2 return Promises. Using bluebird:

functionparseAndMatch(arg1, arg2){
  returnPromise.join(
      asyncCall1(arg1, arg2), 
      asyncCall2(arg1, arg2), 
      (result1, result2) => {
        //do something with result1, result2;return finalResult;
  });
}

If they support callback. Using async.parallel:

functionparseAndMatch(arg1, arg2, callback) {
  async.parallel([
      callback => {
        asyncCall1(arg1, arg2, callback);
      },
      callback => {
        asyncCall2(arg1, arg2, callback);
      },
    ], (err, results) => {
        if (err)
          returncallback(err);
        //do something with result[0], result[1];returncallback(null, results);
    })
}

Post a Comment for "Join All Async Calls To Return Some Result"