Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

make-cancellable-promise

Package Overview
Dependencies
Maintainers
1
Versions
7
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

make-cancellable-promise

Make any Promise cancellable.

  • 1.3.2
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
869K
decreased by-15.38%
Maintainers
1
Weekly downloads
 
Created
Source

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

Keywords

FAQs

Package last updated on 18 Oct 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc