Promise.any()

Baseline 已廣泛支援

此功能已成熟,並可在許多裝置和瀏覽器版本上使用。自 2020 年 9 月起,所有瀏覽器均已提供此功能。

靜態方法 Promise.any() 接收一個可迭代物件(iterable)的 Promises 作為輸入,並返回一個單獨的 Promise。這個返回的 Promise 會在輸入的 Promises 中任何一個 fulfilled(成功)時 fulfilled,並使用該第一個 fulfilled 的 Promise 的值。當輸入的所有 Promises 都 rejected(失敗)時,它會 rejected,並返回一個 AggregateError,其中包含一個 rejection reasons 陣列。

試一試

const promise1 = Promise.reject(new Error("error"));
const promise2 = new Promise((resolve) => setTimeout(resolve, 100, "quick"));
const promise3 = new Promise((resolve) => setTimeout(resolve, 500, "slow"));

const promises = [promise1, promise2, promise3];

Promise.any(promises).then((value) => console.log(value));

// Expected output: "quick"

語法

js
Promise.any(iterable)

引數

iterable

一個 promise 的 可迭代物件(例如 Array)。

返回值

一個 Promise,它

  • 如果傳入的可迭代物件為空,則已 rejected
  • 當給定可迭代物件中的任何一個 Promise fulfilled 時,非同步 fulfilled。fulfilled 的值是第一個 fulfilled 的 Promise 的值。
  • 當給定可迭代物件中的所有 Promise 都 rejected 時,非同步 rejected。rejection 原因是其 errors 屬性中包含 rejection reasons 陣列的 AggregateError。錯誤按傳入 Promises 的順序排列,與完成順序無關。如果傳入的可迭代物件非空但其中不包含待處理的 Promise,則返回的 Promise 仍然是非同步(而不是同步)rejected。

描述

Promise.any() 方法是 Promise 併發方法之一。此方法對於返回第一個 fulfilled 的 Promise 非常有用。它會在一個 Promise fulfilled 後短路,因此一旦找到一個 Promise fulfilled,它就不會等待其他 Promises 完成。

與返回 Promise fulfilled 值陣列Promise.all() 不同,我們只得到一個 fulfilled 值(假設至少有一個 Promise fulfilled)。如果只需要一個 Promise fulfilled 且不關心是哪一個,這會很有好處。請注意另一個區別:此方法在接收到空的可迭代物件時 rejected,因為實際上該可迭代物件中沒有 fulfilled 的項。你可以將 Promise.any()Promise.all()Array.prototype.some()Array.prototype.every() 進行比較。

同樣,與返回第一個已結算(fulfilled 或 rejected)值的 Promise.race() 不同,此方法返回第一個fulfilled的值。此方法會忽略所有 rejected 的 Promises,直到遇到第一個 fulfilled 的 Promise。

示例

使用 Promise.any()

Promise.any() 會以第一個 fulfilled 的 Promise 來 fulfilled,即使有 Promise 先 rejected。這與 Promise.race() 不同,後者會以第一個已結算的 Promise 來 fulfilled 或 rejected。

js
const pErr = new Promise((resolve, reject) => {
  reject(new Error("Always fails"));
});

const pSlow = new Promise((resolve, reject) => {
  setTimeout(resolve, 500, "Done eventually");
});

const pFast = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, "Done quick");
});

Promise.any([pErr, pSlow, pFast]).then((value) => {
  console.log(value);
  // pFast fulfills first
});
// Logs:
// Done quick

使用 AggregateError 進行 rejection

如果沒有任何 Promise fulfilled,Promise.any() 會以 AggregateError rejected。

js
const failure = new Promise((resolve, reject) => {
  reject(new Error("Always fails"));
});

Promise.any([failure]).catch((err) => {
  console.log(err);
});
// AggregateError: No Promise in Promise.any was resolved

顯示載入的第一個圖片

在此示例中,我們有一個函式,它獲取一個圖片並返回一個 blob。我們使用 Promise.any() 來獲取幾張圖片,並顯示第一個可用的圖片(即其 Promise 已 resolved 的圖片)。

js
async function fetchAndDecode(url, description) {
  const res = await fetch(url);
  if (!res.ok) {
    throw new Error(`HTTP error! status: ${res.status}`);
  }
  const data = await res.blob();
  return [data, description];
}

const coffee = fetchAndDecode("coffee.jpg", "Coffee");
const tea = fetchAndDecode("tea.jpg", "Tea");

Promise.any([coffee, tea])
  .then(([blob, description]) => {
    const objectURL = URL.createObjectURL(blob);
    const image = document.createElement("img");
    image.src = objectURL;
    image.alt = description;
    document.body.appendChild(image);
  })
  .catch((e) => {
    console.error(e);
  });

規範

規範
ECMAScript® 2026 語言規範
# sec-promise.any

瀏覽器相容性

另見