UNPKG

parallel-universe

Version:

The set of async flow control structures and promise utils.

57 lines (54 loc) 1.69 kB
'use strict'; /** * The promise that can be aborted. * * @template T The value that the promise is resolved with. */ class AbortablePromise extends Promise { static get [Symbol.species]() { return Promise; } /** * Creates a new abortable promise. * * @param executor A callback that initializes the promise. * @template T The value that the promise is resolved with. */ constructor(executor) { const abortController = new AbortController(); super((resolve, reject) => { abortController.signal.addEventListener('abort', () => { reject(abortController.signal.reason); }); executor(resolve, reject, abortController.signal); }); this._abortController = abortController; } /** * Aborts the signal passed to the executor and instantly rejects the promise with the reason. * * @param reason The abort reason. If not explicitly provided, it defaults to an * {@link https://developer.mozilla.org/en-US/docs/Web/API/DOMException#aborterror AbortError}. */ abort(reason) { this._abortController.abort(reason); } /** * Subscribes this promise to be aborted when the signal is aborted. * * @param signal The signal that aborts this promise. * @returns This promise. */ withSignal(signal) { if (signal.aborted) { this.abort(signal.reason); } else { signal.addEventListener('abort', () => { this.abort(signal.reason); }); } return this; } } exports.AbortablePromise = AbortablePromise;