simple-abortable-promise
TypeScript icon, indicating that this package has built-in type declarations

1.1.1 • Public • Published

simple-abortable-promise Build Status Coverage Status

A Simple Implementation of Abortable Promise

Overview

This library provides a deadly simple 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 simple-abortable-promise

How to use?

Creating

There are 2 ways to create an AbortablePromise:

Constructor

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

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, abortSignal) => {
    fetch(url, { signal: abortSignal })
      .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, abortSignal) => {
  abortSignal.addEventListener('abort', () => {
    // Do something
  });
  // ...
});

More

More background explain is available on my blog.

Package Sidebar

Install

npm i simple-abortable-promise

Weekly Downloads

90

Version

1.1.1

License

MIT

Unpacked Size

7.66 kB

Total Files

6

Last publish

Collaborators

  • zzdjk6