0

我有多个承诺获取不同的资产。我想实现:

  1. 首先执行一些代码以通过then().
  2. 当一切都得到解决/获取时,执行一些通过Promise.all().then().

我需要确保在 2 之前执行 1。从我测试的结果来看,它似乎确实有效。

// handle promises one by one
promise1.then(results => {});
promise2.then(results => {});

// common process that should come after the above then()s
Promise.all([promise1, promise2])
    .then(results => {});

但我可以依赖它吗?“ singlethen() 总是在 a then()on之前执行Promise.all()吗?

4

2 回答 2

4

虽然 Promise.all 因等待所有的 Promise 完成而被停止,但不能保证它会在.then调用最后解决的 Promise 后解决。

相反,您应该尝试从.then调用中创建新的 Promise。

// handle promises one by one
const promise3 = promise1.then(results => {});
const promise4 = promise2.then(results => {});

// common process that should come after the above then()s
Promise.all([promise3, promise4])
    .then(results => {});

这样你就可以保证 Promise all 将在 then 调用后解决

于 2021-10-25T08:24:52.433 回答
1

您可以使用 Async/await 来解决。通过等待每个承诺,您可以在最后编写代码来处理数据。

例子:

(async () => {
  const responses = [];
  await new Promise((res) => res("promise1")).then((res) => {
    console.log("From promise1 first then");
    responses.push(res);
  });

  // Code at the end to do after all promises
  console.log("Coming from second");
  console.log("Responses:", responses);
})();

于 2021-10-25T08:52:29.307 回答