AbortSignal: any() 静的メソッド

Baseline 2024
Newly available

Since March 2024, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

メモ: この機能はウェブワーカー内で利用可能です。

AbortSignal.any() は静的メソッドで、中止シグナルが入った反復可能オブジェクトを受け取り、AbortSignal を返します。返される中止シグナルは、渡された反復可能オブジェクト内の中止シグナルのいずれかが中止された時中止されます。中止の理由は、中止された最初のシグナルの理由に設定されます。渡された中止シグナルのいずれかが既に中止されている場合は、既に中止と設定されている AbortSignal を返します。

構文

js
AbortSignal.any(iterable)

引数

iterable

中止シグナルが入った反復可能オブジェクト (Array など) です。

返値

以下の性質を持つ AbortSignal です。

  • 渡された中止シグナルのいずれかが既に中止されている場合、既に中止されています。返される AbortSignal の理由は、既に中止されている最初の中止シグナルの reason に設定されています。
  • iterable 内の中止シグナルのいずれかが中止された時、非同期で中止されますreason は、最初に中止された中止シグナルの理由に設定されます。

AbortSignal.any() の使用

この例では、AbortController 由来のシグナルと、AbortSignal.timeout 由来のタイムアウトシグナルの両方を組み合わせるデモを行います。

js
const cancelDownloadButton = document.getElementById("cancelDownloadButton");

const userCancelController = new AbortController();

cancelDownloadButton.addEventListener("click", () => {
  userCancelController.abort();
});

// 5 分後にタイムアウトする
const timeoutSignal = AbortSignal.timeout(1_000 * 60 * 5);

// このシグナルは、ユーザーがキャンセルボタンをクリックするか、
// 5 分経過するかのいずれか早いタイミングで中止します
const combinedSignal = AbortSignal.any([
  userCancelController.signal,
  timeoutSignal,
]);

try {
  const res = await fetch(someUrlToDownload, {
    // いずれかのシグナルが中止されたら、フェッチを止める
    signal: combinedSignal,
  });
  const body = await res.blob();
  // ダウンロードした内容を処理する:
  // ...
} catch (e) {
  if (e.name === "AbortError") {
    // ユーザーがキャンセルした
  } else if (e.name === "TimeoutError") {
    // ダウンロードがタイムアウトしたことをユーザーに示す
  } else {
    // その他のエラー (ネットワークエラーなど)
  }
}

仕様書

Specification
DOM
# dom-abortsignal-any

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
any() static method

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
No support
No support
Has more compatibility info.