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

1.4.3 • Public • Published

abortable-promise

Yet another implementation of Abortable Promise

Overview

This library provides another implementation of making Promise abortable.

That is, an AbortablePromise is a Promise with the abitlity to be aborted.

When an AbortablePromise is aborted, it will reject with an AbortError.

How to install?

npm install @xuchaoqian/abortable-promise

How to use?

Creating

There are 2 ways to create an AbortablePromise:

Constructor

const abortablePromise = new AbortablePromise<T>((resolve, reject, signal) => {
  // ...
});

Create from an existing Promise

const abortablePromise = AbortablePromise.from(promise);

Abort

// Abort with default reason - Aborted
abortablePromise.abort();

// Abort with custom reason
abortablePromise.abort("I abort it");

Receipes

Use with fetch

const loadData = (id: number) => {
  retrun new AbortablePromise<Data>((resolve, reject, signal) => {
    fetch(url, { signal })
      .then(response => response.json())
      .then(parseJsonToData)
      .then(resolve)
      .catch(reject);
  });
}

const abortablePromise = loadData(id);
abortablePromise.abort();

Do something more when abort

const abortablePromise = new AbortablePromise<Data>(
  (resolve, reject, signal) => {
    signal.addEventListener("abort", () => {
      // Do something
    });
    // ...
  }
);

More

More background explain is available on zzdjk6's blog.

Package Sidebar

Install

npm i @xuchaoqian/abortable-promise

Weekly Downloads

31

Version

1.4.3

License

MIT

Unpacked Size

12.7 kB

Total Files

12

Last publish

Collaborators

  • xuchaoqian