File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change @@ -245,3 +245,43 @@ cancelableXHR.abortPromise(xhrPromise);// <2>
245245Promiseは処理のフローを制御する力に優れているため、
246246それを最大限活かすためには一つの関数でやり過ぎないで処理を小さく分けること等、
247247今までのJavaScriptで言われているようなことをより意識していいのかもしれません。
248+
249+ [NOTE]
250+ .Fetch APIでのキャンセル
251+ ====
252+
253+ XHRの現代的なバージョンである https://developer.mozilla.org/ja/docs/Web/API/Fetch_API[Fetch API] では、 https://developer.mozilla.org/en-US/docs/Web/API/AbortController[AbortController] というAPIによってリクエストをキャンセルを実現できます。
254+
255+ Fetch APIでは、次のようにリクエストをキャンセルできます。
256+
257+
258+ [role="executable"]
259+ [source,javascript]
260+ .AbortControllerでのFetchのキャンセル
261+ ----
262+ // AbortControllerのインスタンスの作成
263+ const controller = new AbortController()
264+ // キャンセルを通知するための siganl を取得する
265+ const signal = controller.signal
266+ // signal をfetchメソッドの第二引数に渡す
267+ fetch("https://httpbin.org/get", { signal })
268+ .then((result) => {
269+ // 結果の正常処理
270+ console.log(result);
271+ })
272+ .catch((error) => {
273+ if (error.name == "AbortError") {
274+ // 中断の場合の処理
275+ console.error("Fetchが中断されました", error);
276+ return;
277+ }
278+ // 中断以外のエラー
279+ console.error(err);
280+ })
281+ // Fetchをキャンセルする
282+ controller.abort();
283+ ----
284+
285+ ``AbortController``という今回実装したものと似たような操作メソッドをもつオブジェクトを利用することがわかります。
286+
287+ ====
You can’t perform that action at this time.
0 commit comments