@as-any/abortable-promise
TypeScript icon, indicating that this package has built-in type declarations

0.0.7 • Public • Published

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 });

Dependencies (0)

    Dev Dependencies (10)

    Package Sidebar

    Install

    npm i @as-any/abortable-promise

    Weekly Downloads

    3

    Version

    0.0.7

    License

    MIT

    Unpacked Size

    13.7 kB

    Total Files

    33

    Last publish

    Collaborators

    • npm-as-any
    • v-zo-as-any
    • doomsoft
    • vpzorin
    • vzorin