使用多个 await()

Using multiple await()

假设我有两个承诺。通常,在所有这些承诺完成之前,代码无法执行。在我的代码中,假设我有 promise1 和 promise 2 然后我有 await promise1await promise2。在这两个承诺完成之前,我的代码不会执行。但是我需要的是,如果这两个中的一个完成,那么代码可以执行,然后我们可以忽略另一个。 这是可能的,因为代码只需要其中一个等待成功。这可以在 javascript (nodejs) 中实现吗?

Promise.any 是您要查找的内容:

Promise.any() takes an iterable of Promise objects. It returns a single promise that resolves as soon as any of the promises in the iterable fulfills, with the value of the fulfilled promise. If no promises in the iterable fulfill (if all of the given promises are rejected), then the returned promise is rejected with an AggregateError, a new subclass of Error that groups together individual errors.

示例:

const randomDelay = (num) => new Promise((resolve) => setTimeout(() => {
  console.log(`${num} is done now`);
  resolve(`Random Delay ${num} has finished`);
}, Math.random() * 1000 * 10));

(async() => {
  console.log("Starting...");
  const result = await Promise.any(new Array(5).fill(0).map((_, index) => randomDelay(index)));
  console.log(result);
  console.log("Continuing...");

})();

您可以使用Promise.any()功能。您可以传递一个 Promise 数组作为输入,它会在第一个 Promise 解析时立即解析。

(async() => {
  let promises = [];
  promises.push(new Promise((resolve) => setTimeout(resolve, 100, 'quick')))
  promises.push(new Promise((resolve) => setTimeout(resolve, 500, 'slow')))

  const result = await Promise.any(promises);
  console.log(result)
})()

Promise.race()Promise.any()

  • 如果其中一个承诺的状态发生了 rejectedfulfilled 的变化,您可以使用 Promise.race()
  • 如果您希望其中一个承诺是 fulfilled,您应该使用 Promise.any()

Promise.any 可以继续执行其他代码,如果任何一个承诺将被解决。

let i = 1;
const newPromise = () => {
    return new Promise((resolve) => {
        setTimeout(() => {
           console.log(`promise${i++} resolved`);
           resolve(true);
        }, Math.random() * 1000)
    });
}

(async() => {
    await Promise.any([newPromise(), newPromise()]);
    console.log("Code will executes if any promise resolved");
})()