@as-any/abortable-promise
v0.0.7
Published
An extension of native Promises with true abort capabilities via AbortSignal.
Downloads
26
Readme
AbortablePromise
The AbortablePromise
class is an extension of the native JavaScript Promise
, designed to make it easier to abort promises. It adds an abort signal to the promise, which can trigger rejection of the promise when it's aborted.
How to Use
Create AbortController and pass its signal
as a second argument of AbortablePromise
constructor:
const controller = new AbortController();
const signal = controller.signal;
const myPromise = new AbortablePromise((resolve, reject) => {
// Do something
}, signal);
Or make your existing promise abortable:
const originalPromise = new Promise((resolve, reject) => {
// Do something
});
const myAbortablePromise = makeAbortable(originalPromise, signal);
Then call the abort()
method
controller.abort();
Error handling can be done using the catch
method just like with regular promises:
myAbortablePromise.catch(reason => {
console.error('Promise was aborted:', reason);
});
By default, AbortablePromise
rejects with an "AbortError" DOMException if it is aborted:
setTimeout(() => controller.abort(), 1000);
try {
await myAbortablePromise;
} catch (err) {
if (err.name === 'AbortError') {
console.log("Operation aborted: ", err.message);
}
console.log("Error occurred: ", err);
}
Pass any custom object you want the promise to be rejected with to controller.abort()
:
myAbortablePromise.catch(reason => {
console.log(reason) // { myReason: 42 }
})
controller.abort({ myReason: 42 });