Installations
npm install p-cancelable
Developer Guide
Typescript
Yes
Module System
ESM
Min. Node Version
>=14.16
Node Version
16.15.0
NPM Version
8.3.2
Score
99.8
Supply Chain
99.5
Quality
75.8
Maintenance
100
Vulnerability
100
License
Releases
Contributors
Unable to fetch Contributors
Languages
JavaScript (82.26%)
TypeScript (17.74%)
Love this project? Help keep it running — sponsor us today! 🚀
Developer
sindresorhus
Download Statistics
Total Downloads
4,360,573,546
Last Day
3,792,398
Last Week
20,151,080
Last Month
87,736,144
Last Year
946,089,466
GitHub Statistics
MIT License
441 Stars
53 Commits
22 Forks
8 Watchers
1 Branches
12 Contributors
Updated on Feb 11, 2025
Package Meta Information
Latest Version
4.0.1
Package Id
p-cancelable@4.0.1
Unpacked Size
13.30 kB
Size
4.35 kB
File Count
5
NPM Version
8.3.2
Node Version
16.15.0
Total Downloads
Cumulative downloads
Total Downloads
4,360,573,546
Last Day
-0.4%
3,792,398
Compared to previous day
Last Week
-3.3%
20,151,080
Compared to previous week
Last Month
35.6%
87,736,144
Compared to previous month
Last Year
9.6%
946,089,466
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
p-cancelable
Create a promise that can be canceled
Useful for animation, loading resources, long-running async computations, async iteration, etc.
If you target Node.js 16 or later, this package is less useful and you should probably use AbortController
instead.
Install
1npm install p-cancelable
Usage
1import PCancelable from 'p-cancelable'; 2 3const cancelablePromise = new PCancelable((resolve, reject, onCancel) => { 4 const worker = new SomeLongRunningOperation(); 5 6 onCancel(() => { 7 worker.close(); 8 }); 9 10 worker.on('finish', resolve); 11 worker.on('error', reject); 12}); 13 14// Cancel the operation after 10 seconds 15setTimeout(() => { 16 cancelablePromise.cancel('Unicorn has changed its color'); 17}, 10000); 18 19try { 20 console.log('Operation finished successfully:', await cancelablePromise); 21} catch (error) { 22 if (cancelablePromise.isCanceled) { 23 // Handle the cancelation here 24 console.log('Operation was canceled'); 25 return; 26 } 27 28 throw error; 29}
API
new PCancelable(executor)
Same as the Promise
constructor, but with an appended onCancel
parameter in executor
.
Cancelling will reject the promise with CancelError
. To avoid that, set onCancel.shouldReject
to false
.
1import PCancelable from 'p-cancelable'; 2 3const cancelablePromise = new PCancelable((resolve, reject, onCancel) => { 4 const job = new Job(); 5 6 onCancel.shouldReject = false; 7 onCancel(() => { 8 job.stop(); 9 }); 10 11 job.on('finish', resolve); 12}); 13 14cancelablePromise.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.fn(fn)
Convenience method to make your promise-returning or async function cancelable.
The function you specify will have onCancel
appended to its parameters.
1import PCancelable from 'p-cancelable'; 2 3const fn = PCancelable.fn((input, onCancel) => { 4 const job = new Job(); 5 6 onCancel(() => { 7 job.cleanup(); 8 }); 9 10 return job.start(); //=> Promise 11}); 12 13const cancelablePromise = fn('input'); //=> PCancelable 14 15// … 16 17cancelablePromise.cancel();
CancelError
Type: Error
Rejection reason when .cancel()
is called.
It includes a .isCanceled
property for convenience.
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-cancelable for enterprise
Available as part of the Tidelift Subscription.
The maintainers of p-cancelable and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.
Related
- p-progress - Create a promise that reports progress
- p-lazy - Create a lazy promise that defers execution until
.then()
or.catch()
is called - More…

No vulnerabilities found.
Reason
no binaries found in the repo
Reason
security policy file detected
Details
- Info: security policy file detected: .github/security.md:1
- Info: Found linked content: .github/security.md:1
- Info: Found disclosure, vulnerability, and/or timelines in security policy: .github/security.md:1
- Info: Found text in security policy: .github/security.md:1
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
- Info: project has a license file: license:0
- Info: FSF or OSI recognized license: MIT License: license:0
Reason
0 existing vulnerabilities detected
Reason
Found 10/30 approved changesets -- score normalized to 3
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/main.yml:1
- Info: no jobLevel write permissions found
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:17: update your workflow using https://app.stepsecurity.io/secureworkflow/sindresorhus/p-cancelable/main.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:18: update your workflow using https://app.stepsecurity.io/secureworkflow/sindresorhus/p-cancelable/main.yml/main?enable=pin
- Warn: npmCommand not pinned by hash: .github/workflows/main.yml:22
- Info: 0 out of 2 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 1 npmCommand dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'main'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 10 are checked with a SAST tool
Score
4.3
/10
Last Scanned on 2025-02-10
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More