1.1.1 • Published 4 years ago

simple-abortable-promise v1.1.1

Weekly downloads
57
License
MIT
Repository
github
Last release
4 years ago

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.