@jcoreio/abortable
Version:
memory-leak-proof function to wrap a promise to reject when a signal is aborted
47 lines (46 loc) • 1.56 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.abortable = abortable;
exports.newAbortError = void 0;
var newAbortError = exports.newAbortError = function newAbortError() {
return new DOMException('This operation was aborted', 'AbortError');
};
var noop = function noop() {};
function abortable(promise, signal) {
if (!signal) return promise;
return new Promise(function (resolve, reject) {
var cleanup = function cleanup() {
var callbacks = {
resolve: resolve,
reject: reject
};
// Prevent memory leaks. If the input promise never resolves, then the handlers
// below would retain this enclosing Promise's resolve and reject callbacks,
// which would retain the enclosing Promise and anything waiting on it.
// By replacing references to these callbacks, we enable the enclosing Promise to
// be garbage collected
resolve = noop;
reject = noop;
// Memory could also leak if the signal never aborts, unless we remove the abort
// handler
signal.removeEventListener('abort', onAbort);
return callbacks;
};
var onAbort = function onAbort() {
return cleanup().reject(newAbortError());
};
promise.then(function (value) {
return cleanup().resolve(value);
}, function (error) {
return cleanup().reject(error);
});
if (signal.aborted) {
reject(newAbortError());
} else {
signal.addEventListener('abort', onAbort);
}
});
}
//# sourceMappingURL=index.js.map