Socket
Socket
Sign inDemoInstall

p-cancelable

Package Overview
Dependencies
0
Maintainers
1
Versions
15
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    p-cancelable

Create a promise that can be canceled


Version published
Weekly downloads
18M
decreased by-0.9%
Maintainers
1
Install size
8.60 kB
Created
Weekly downloads
 

Package description

What is p-cancelable?

The p-cancelable package provides a way to create cancelable promises in JavaScript. This is particularly useful for managing asynchronous operations that may need to be canceled before they complete, such as HTTP requests, long-running computations, or any other task that might not need to continue executing if certain conditions are met.

What are p-cancelable's main functionalities?

Creating a cancelable promise

This feature allows the creation of a new cancelable promise. The promise can be canceled at any time before it resolves or rejects, which triggers the onCancel function where cleanup operations like clearing timeouts or aborting requests can be performed.

const PCancelable = require('p-cancelable');

const myCancelablePromise = new PCancelable((resolve, reject, onCancel) => {
  const timer = setTimeout(() => {
    resolve('Done!');
  }, 2000);

  onCancel(() => {
    clearTimeout(timer);
    reject(new Error('Operation canceled.'));
  });
});

myCancelablePromise.cancel();

Other packages similar to p-cancelable

Readme

Source

p-cancelable Build Status

Create a promise that can be canceled

Useful for animation, loading resources, long-running async computations, async iteration, etc.

Install

$ npm install p-cancelable

Usage

const PCancelable = require('p-cancelable');

const cancelablePromise = new PCancelable((resolve, reject, onCancel) => {
	const worker = new SomeLongRunningOperation();

	onCancel(() => {
		worker.close();
	});

	worker.on('finish', resolve);
	worker.on('error', reject);
});

(async () => {
	try {
		console.log('Operation finished successfully:', await cancelablePromise);
	} catch (error) {
		if (cancelablePromise.isCanceled) {
			// Handle the cancelation here
			console.log('Operation was canceled');
			return;
		}

		throw error;
	}
})();

// Cancel the operation after 10 seconds
setTimeout(() => {
	cancelablePromise.cancel('Unicorn has changed its color');
}, 10000);

API

new PCancelable(executor)

Same as the Promise constructor, but with an appended onCancel parameter in executor.
Cancelling will reject the promise with PCancelable.CancelError. To avoid that, set onCancel.shouldReject to false.

const cancelable = new PCancelable((resolve, reject, onCancel) => {
	const job = new Job();

	onCancel.shouldReject = false;
	onCancel(() => {
		job.stop();
	});

	job.on('finish', resolve);
});

promise.cancel(); // Doesn't throw an error

PCancelable is a subclass of Promise.

onCanceled(fn)

Type: Function

Accepts a function that is called when the promise is canceled.

You're not required to call this function. You can call this function multiple times to add multiple cancel handlers.

PCancelable#cancel([reason])

Type: Function

Cancel the promise and optionally provide a reason.

The cancellation is synchronous. Calling it after the promise has settled or multiple times does nothing.

PCancelable#isCanceled

Type: boolean

Whether the promise is canceled.

PCancelable.CancelError

Type: Error

Rejection reason when .cancel() is called.

It includes a .isCanceled property for convenience.

PCancelable.fn(fn)

Convenience method to make your promise-returning or async function cancelable.

The function you specify will have onCancel appended to its parameters.

const fn = PCancelable.fn((input, onCancel) => {
	const job = new Job();

	onCancel(() => {
		job.cleanup();
	});

	return job.start(); //=> Promise
});

const promise = fn('input'); //=> PCancelable

// …

promise.cancel();

FAQ

Cancelable vs. Cancellable

In American English, the verb cancel is usually inflected canceled and canceling—with one l.
Both a browser API and the Cancelable Promises proposal use this spelling.

What about the official Cancelable Promises proposal?

It's still an early draft and I don't really like its current direction. It complicates everything and will require deep changes in the ecosystem to adapt to it. And the way you have to use cancel tokens is verbose and convoluted. I much prefer the more pragmatic and less invasive approach in this module. The proposal was withdrawn.

  • p-progress - Create a promise that reports progress
  • p-lazy - Create a lazy promise that defers execution until .then() or .catch() is called
  • More…

License

MIT © Sindre Sorhus

Keywords

FAQs

Last updated on 10 Sep 2018

Did you know?

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

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc