Skip to content

Wrap promise function into cancelable promise function

License

Notifications You must be signed in to change notification settings

preco21/pcancel

Repository files navigation

pcancel

Code Style Prev NPM Version Build Status Dependency Status

Wrap promise function into cancelable promise function

Sometimes you may need to create cancelable promise for situation like to avoid isMounted antipattern in React. pcancel provides simple utility for creating cancelable promises. Highly inspired from this comment.

Install

$ npm install pcancel

Usage

import pcancel from 'pcancel';

const delayC = pcancel(delay);
const p = delayC(4000)
  .promise
  .then(() => console.log('Yey!'))
  .catch((err) => console.error(err));

p.cancel(); // Error: Promise has canceled

function delay(time) {
  return new Promise((resolve) => setTimeout(() => resolve(), time));
}

API

pcancel(fn[, options])

  • fn Function - Promise-returning function that will be cancelable.
  • options Object (optional)
    • noReject Boolean - Whether to reject when canceling. If this option is true, the promise will be resolved with the value passed through to cancel() method on the promise.

Returns a wrapped function that returns object includes Promise instance and cancel() function.

You can also specify error or value through cancel() method, the specified value will be returned instead of value of the promise:

p.cancel(new Error('Foo')); // Error: Foo

Note: cancel() rejects the promise immediately when it called.

License

MIT

About

Wrap promise function into cancelable promise function

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published