@jcoreio/abortable
Version:
memory-leak-proof function to wrap a promise to reject when a signal is aborted
2 lines (1 loc) • 2.53 kB
Source Map (JSON)
{"version":3,"file":"index.mjs","names":["newAbortError","DOMException","noop","abortable","promise","signal","Promise","resolve","reject","cleanup","callbacks","removeEventListener","onAbort","then","value","error","aborted","addEventListener"],"sources":["src/index.ts"],"sourcesContent":["export const newAbortError = () =>\n new DOMException('This operation was aborted', 'AbortError')\n\nconst noop = () => {}\n\nexport function abortable<T>(\n promise: Promise<T>,\n signal: AbortSignal | undefined\n): Promise<T> {\n if (!signal) return promise\n return new Promise<T>((resolve, reject) => {\n const cleanup = () => {\n const callbacks = { resolve, reject }\n // Prevent memory leaks. If the input promise never resolves, then the handlers\n // below would retain this enclosing Promise's resolve and reject callbacks,\n // which would retain the enclosing Promise and anything waiting on it.\n // By replacing references to these callbacks, we enable the enclosing Promise to\n // be garbage collected\n resolve = noop\n reject = noop\n // Memory could also leak if the signal never aborts, unless we remove the abort\n // handler\n signal.removeEventListener('abort', onAbort)\n return callbacks\n }\n const onAbort = () => cleanup().reject(newAbortError())\n\n promise.then(\n (value) => cleanup().resolve(value),\n (error) => cleanup().reject(error)\n )\n if (signal.aborted) {\n reject(newAbortError())\n } else {\n signal.addEventListener('abort', onAbort)\n }\n })\n}\n"],"mappings":"AAAA,OAAO,MAAMA,aAAa,GAAGA,CAAA,KAC3B,IAAIC,YAAY,CAAC,4BAA4B,EAAE,YAAY,CAAC;AAE9D,MAAMC,IAAI,GAAGA,CAAA,KAAM,CAAC,CAAC;AAErB,OAAO,SAASC,SAASA,CACvBC,OAAmB,EACnBC,MAA+B,EACnB;EACZ,IAAI,CAACA,MAAM,EAAE,OAAOD,OAAO;EAC3B,OAAO,IAAIE,OAAO,CAAI,CAACC,OAAO,EAAEC,MAAM,KAAK;IACzC,MAAMC,OAAO,GAAGA,CAAA,KAAM;MACpB,MAAMC,SAAS,GAAG;QAAEH,OAAO;QAAEC;MAAO,CAAC;MACrC;MACA;MACA;MACA;MACA;MACAD,OAAO,GAAGL,IAAI;MACdM,MAAM,GAAGN,IAAI;MACb;MACA;MACAG,MAAM,CAACM,mBAAmB,CAAC,OAAO,EAAEC,OAAO,CAAC;MAC5C,OAAOF,SAAS;IAClB,CAAC;IACD,MAAME,OAAO,GAAGA,CAAA,KAAMH,OAAO,CAAC,CAAC,CAACD,MAAM,CAACR,aAAa,CAAC,CAAC,CAAC;IAEvDI,OAAO,CAACS,IAAI,CACTC,KAAK,IAAKL,OAAO,CAAC,CAAC,CAACF,OAAO,CAACO,KAAK,CAAC,EAClCC,KAAK,IAAKN,OAAO,CAAC,CAAC,CAACD,MAAM,CAACO,KAAK,CACnC,CAAC;IACD,IAAIV,MAAM,CAACW,OAAO,EAAE;MAClBR,MAAM,CAACR,aAAa,CAAC,CAAC,CAAC;IACzB,CAAC,MAAM;MACLK,MAAM,CAACY,gBAAgB,CAAC,OAAO,EAAEL,OAAO,CAAC;IAC3C;EACF,CAAC,CAAC;AACJ","ignoreList":[]}