简体   繁体   中英

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!'));

Just return Promise.all(...

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM