Abortable fetch
signal は Request インターフェイスの読み取り専用プロパティで、このリクエストに関連付けられた AbortSignal を返します。
対応ブラウザ
| 機能 | デスクトップ | モバイル | ||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS | |
| 66 | 16 | 57 | 12.1 | 66 | 12.2 | |
init_signal_parameter `init.signal` パラメータ | 66 | 16 | 57 | 11.1 | 66 | 11.3 |
基本構文
JAVASCRIPT
// Create a new abort controller
const controller = new AbortController();
// Create a request with this controller's AbortSignal object
const req = new Request("/", { signal: controller.signal });
// Add an event handler logging a message in case of abort
req.signal.addEventListener("abort", () => {
console.log("abort");
});
// In case of abort, log the AbortSignal reason, if any
fetch(req).catch(() => {
if (req.signal.aborted) {
if (req.signal.reason) {
console.log(`Request aborted with reason: ${req.signal.reason}`);
} else {
console.log("Request aborted but no reason was given.");
}
} else {
console.log("Request not aborted, but terminated abnormally.");
}
});
// Actually abort the request
controller.abort(); 実務での使いどころ
-
Abortable fetch の活用
signal は Request インターフェイスの読み取り専用プロパティで、このリクエストに関連付けられた AbortSignal を返します。
注意点
- 古いブラウザでは対応していない場合がある。
実装メモ
- 一部の API はセキュアコンテキスト (HTTPS) やユーザー操作起点を必要とする。利用前に要件を確認すること。