我如何等待 2 个承诺完成,再 运行 个?

How can I wait for 2 promises to complete, to run another?

我正在尝试 运行 两个承诺:

Promise.all([...])

但他们都有自己的.then:

Promise.all([promise1().then(...), promise2().then(...)])

我希望在 Promise.all 上 运行 另一个 .then,同时也在等待 .then 到 return,如果这有意义的话。

这里 fiddle 表达了我的意思。

如果您想在 javascript 中使用异步操作,您可以使用 3 种方法。

  1. 回调
  2. 承诺
  3. async/await

为了准确实现您想要的东西,最好和优化的方法是使用 async/await 方法。

你可以这样做:

      async function getAllData(){

      const p1 = await promise1;
      const p2 = await promise2;
       
      }

now getAllData return Promise,您可以使用 .then() 获取结果并使用 .catch() 获取错误。

要阅读有关语法和其他功能的更多信息,您可以访问此站点:explain about async and await

如果你运行

function get1() {
  return new Promise((r)=>setTimeout(() => r(),3000))
}

function rejection() {/*Handle rejection*/}

function doAll(...ps) {
    return Promise.all(ps.map(rejection))
}

(async () => {
  var p1 = get1().then(()=>console.log("1"));
  var p2 = get1().then(()=>console.log("2"));
    Promise.all([p1, p2]).then(()=>{
    console.log("3")
  })
})()

则结果正确

1

2

3

If you run

function get1() {
  return new Promise((r)=>setTimeout(() => r(),3000))
}

function rejection() {/*Handle rejection*/}

function doAll(...ps) {
    return Promise.all(ps)
}

(async () => {
  var p1 = get1().then(()=>console.log("1"));
  var p2 = get1().then(()=>console.log("2"));
    doAll(p1, p2).then(()=>{
    console.log("3")
  })
})()

然后你又得到正确的

1

2

3

因此,问题出在ps.map(rejection)的部分。让我们看看:

function get1() {
  return new Promise((r)=>setTimeout(() => r(),3000))
}

function rejection() {/*Handle rejection*/}

function doAll(...ps) {
    console.log(ps);
  console.log(ps.map(rejection));
    return Promise.all(ps.map(rejection));
}

(async () => {
  var p1 = get1().then(()=>console.log("1"));
  var p2 = get1().then(()=>console.log("2"));
    doAll(p1, p2).then(()=>{
    console.log("3")
  })
})()

输出

两个元素的数组,都是 undefined 是微不足道的评估。因为 ps.map(rejection) 是一个箭头函数,它命名了它的参数 rejection 并且没有 return 任何东西。