1. make-cancellable-promise
Make any Promise cancellable.
make-cancellable-promise
Package: make-cancellable-promise
Created by: wojtekmaj
Last modified: Wed, 18 Oct 2023 13:22:48 GMT
Version: 1.3.2
License: MIT
Downloads: 3,216,151
Repository: https://github.com/wojtekmaj/make-cancellable-promise

Install

npm install make-cancellable-promise
yarn add make-cancellable-promise

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

RELATED POST

10 Must-Know Windows Shortcuts That Will Save You Time

10 Must-Know Windows Shortcuts That Will Save You Time

Arrays vs Linked Lists: Which is Better for Memory Management in Data Structures?

Arrays vs Linked Lists: Which is Better for Memory Management in Data Structures?

Navigating AWS Networking: Essential Hacks for Smooth Operation

Navigating AWS Networking: Essential Hacks for Smooth Operation

Achieving Stunning Visuals with Unity's Global Illumination

Achieving Stunning Visuals with Unity's Global Illumination

Nim's Hidden Gems: Lesser-known Features for Writing Efficient Code

Nim's Hidden Gems: Lesser-known Features for Writing Efficient Code