Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to chain a Promise.all with other Promises?

I want to execute my code in the following order:

  1. Promise 1
  2. Wait for 1 to be done, then do Promise 2+3 at the same time
  3. Final function waits for Promise 2+3 to be done

I'm having some trouble figuring it out, my code so far is below.

function getPromise1() {
  return new Promise((resolve, reject) => {
    // do something async
    resolve('myResult');
  });
}

function getPromise2() {
  return new Promise((resolve, reject) => {
    // do something async
    resolve('myResult');
  });
}

function getPromise3() {
  return new Promise((resolve, reject) => {
    // do something async
    resolve('myResult');
  });
}

getPromise1()
.then(
  Promise.all([getPromise2(), getPromise3()])
  .then() // ???
)
.then(() => console.log('Finished!'));
like image 287
ABC Avatar asked Apr 21 '16 03:04

ABC


People also ask

How do you run multiple promises together?

Approach 1: In this approach, we will use Promise. all() method which takes all promises in a single array as its input. As a result, this method executes all the promises in itself and returns a new single promise in which the values of all the other promises are combined together.

Can promise be chained?

Introduction to the JavaScript promise chaining The callback passed to the then() method executes once the promise is resolved. In the callback, we show the result of the promise and return a new value multiplied by two ( result*2 ).

Does promise all resolve promises in order?

Here, Promise. all() method is the order of the maintained promises. The first promise in the array will get resolved to the first element of the output array, the second promise will be a second element in the output array and so on.

Does promise all cancel other promises?

As stated in the comments promises cannot be canceled.


2 Answers

Just return Promise.all(...

getPromise1().then(() => {
  return Promise.all([getPromise2(), getPromise3()]);
}).then((args) => console.log(args)); // result from 2 and 3
like image 187
adeneo Avatar answered Oct 20 '22 01:10

adeneo


I know it's an old thread, but isn't

() => {return Promise.all([getPromise2(), getPromise3()]);}

a little superfluous? The idea of fat arrow is that you can write it as:

() => Promise.all([getPromise2(), getPromise3()])

which makes the resulting code somewhat clearer:

getPromise1().then(() => Promise.all([getPromise2(), getPromise3()]))
.then((args) => console.log(args)); // result from 2 and 3

Anyway, thanks for the answer, I was stuck with this :)

like image 14
Polakko Avatar answered Oct 19 '22 23:10

Polakko