Neurosis Prevention Mechanism
Miss any of our Open RFC calls?Watch the recordings here! »

promise-abortable

1.2.6 • Public • Published

promise-abortable

NPM version node version build status Test coverage Install size NPM download NPM count License

Concept

abort != reject

Features

  • Abort in promise
  • Abort in promise chain
  • Abort for nesting promise
  • Return promise after abort

Use Cases

  • Cancel request when component hide, unmount or destory
  • Cancel long-running async operation
  • Return promise with abort for common request function

Browser Support

Any browser that supports Promise.

Chrome Firefox Safari Opera Edge
33 ✔ 29 ✔ 8 ✔ 20 ✔ 12 ✔
  • Use Babel for lower versions
  • Or include script iife.es3.js below
  • But I think bluebird 3 is a better choice

Install

$ npm install promise-abortable
import AbortablePromise from "promise-abortable";

The IIFE build is also available on unpkg:

<script src="https://unpkg.com/promise-abortable/dist/iife.es5.js"></script> <!-- 1KB, recommend -->
<script src="https://unpkg.com/promise-abortable/dist/iife.es6.js"></script> <!-- 1KB -->
<script src="https://unpkg.com/promise-abortable/dist/iife.es3.js"></script> <!-- 16KB -->

Usage

// 1. Instantiate
const promise = new AbortablePromise((resolve, reject, signal) => {
  // 2. Set abort handler
  signal.onabort = reason => {
    // 4. Abort won't reject, but you can reject manually
  };
});
// 3. Invoke `signal.onabort(reason)`
promise.abort(reason);

Pseudo code

See full examples here.

Abort in promise

const promise = new AbortablePromise(...);
// or: const promise = AbortablePromise.resolve(...);
// or: const promise = AbortablePromise.reject(...);
// or: const promise = AbortablePromise.all([...]);
// or: const promise = AbortablePromise.race([...]);
promise.abort();

Abort in promise chain

const promise = new AbortablePromise(...).then(...).catch(...);
promise.abort();

Abort for nesting promise

const promise = AbortablePromise.resolve(...).then(value => {
  return new AbortablePromise(...);
});
promise.abort();

Return promise after abort

const promise = new AbortablePromise(...);
promise.abort().then(...).catch(...);

Abort in async/await

const promise = new AbortablePromise(...);
(async () => {
  try { await promise; } catch (error) {...}
})();
promise.abort();

Install

npm i promise-abortable

DownloadsWeekly Downloads

746

Version

1.2.6

License

MIT

Unpacked Size

49 kB

Total Files

16

Last publish

Collaborators

  • avatar