make-cancellable-promise
Make any Promise cancellable.
Last updated a year ago by wojtekmaj .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ cnpm install make-cancellable-promise 
SYNC missed versions from official npm registry.

npm downloads CI

Make-Cancellable-Promise

Make any Promise cancellable.

tl;dr

  • Install by executing npm install make-cancellable-promise or yarn add make-cancellable-promise.
  • Import by adding import makeCancellablePromise from 'make-cancellable-promise.
  • Do stuff with it!
    const { promise, cancel } = makeCancellablePromise(myPromise);
    

User guide

makeCancellablePromise(myPromise)

A function that returns an object with two properties:

promise and cancel. promise is a wrapped around your promise. cancel is a function which stops .then() and .catch() from working on promise, even if promise passed to makeCancellablePromise resolves or rejects.

Usage

const { promise, cancel } = makeCancellablePromise(myPromise);

Typically, you'd want to use makeCancellablePromise in React components. If you call setState on an unmounted component, React will throw an error.

Here's how you can use makeCancellablePromise with React:

function MyComponent() {
  const [status, setStatus] = useState('initial');

  useEffect(() => {
    const { promise, cancel } = makeCancellable(fetchData());

    promise.then(() => setStatus('success')).catch(() => setStatus('error'));

    return () => {
      cancel();
    };
  }, []);

  const text = (() => {
    switch (status) {
      case 'pending':
        return 'Fetching…';
      case 'success':
        return 'Success';
      case 'error':
        return 'Error!';
      default:
        return 'Click to fetch';
    }
  })();

  return <p>{text}</p>;
}

License

The MIT License.

Author

Wojciech Maj Wojciech Maj

Current Tags

  • 2.0.0                                ...           latest (a year ago)

8 Versions

  • 2.0.0                                ...           a year ago
  • 1.3.2                                ...           2 years ago
  • 1.3.1                                ...           3 years ago
  • 1.3.0                                ...           3 years ago
  • 1.2.1                                ...           3 years ago
  • 1.2.0                                ...           3 years ago
  • 1.1.0                                ...           5 years ago
  • 1.0.0                                ...           7 years ago
Maintainers (1)
Downloads
Today 0
This Week 0
This Month 3
Last Day 0
Last Week 8
Last Month 7
Dependencies (0)
None
Dev Dependencies (5)
Dependents (1)

Copyright 2013 - present © cnpmjs.org | Home |