How to chain a Promise.all with other Promises?

只谈情不闲聊 提交于 2019-12-04 09:55:43

问题


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

回答1:


Just return Promise.all(...

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



回答2:


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



来源:https://stackoverflow.com/questions/36759061/how-to-chain-a-promise-all-with-other-promises

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!