From 3ce54f07284da146ceb57d1a4a64a041d66344d8 Mon Sep 17 00:00:00 2001 From: Samuel Gratzl Date: Fri, 10 May 2019 14:27:07 +1000 Subject: [PATCH] add abortAbleFetch --- src/abortAble.ts | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/abortAble.ts b/src/abortAble.ts index 5463616..9691052 100644 --- a/src/abortAble.ts +++ b/src/abortAble.ts @@ -84,6 +84,33 @@ export default function abortAble(loader: PromiseLike): IAAP { }; } + +export function abortAbleFetch(input: RequestInfo, init?: RequestInit): IAAP { + const controller = new AbortController(); + + const race = new Promise((resolve, reject) => { + const r = fetch(input, Object.assign({signal: controller.signal}, init || {})); + r.then(resolve); + r.catch((error) => { + if (error instanceof DOMException) { + resolve(ABORTED); + } else { + reject(error); + } + }); + }); + + const abort = controller.abort.bind(controller); + const isAborted = () => controller.signal.aborted; + + return { + then: thenFactory(race, isAborted, abort), + abort, + isAborted + }; +} + + export function abortAbleAll(values: [T1 | IAAP, T2 | IAAP, T3 | IAAP, T4 | IAAP, T5 | IAAP, T6 | IAAP, T7 | IAAP, T8 | IAAP, T9 | IAAP, T10 | IAAP]): IAAP<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; export function abortAbleAll(values: [T1 | IAAP, T2 | IAAP, T3 | IAAP, T4 | IAAP, T5 | IAAP, T6 | IAAP, T7 | IAAP, T8 | IAAP, T9 | IAAP]): IAAP<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; export function abortAbleAll(values: [T1 | IAAP, T2 | IAAP, T3 | IAAP, T4 | IAAP, T5 | IAAP, T6 | IAAP, T7 | IAAP, T8 | IAAP]): IAAP<[T1, T2, T3, T4, T5, T6, T7, T8]>;