What is p-finally?
The p-finally npm package is designed to allow you to attach a handler that will be called when a promise is settled (either fulfilled or rejected). This is useful for running cleanup code or finalizing operations, regardless of the promise's outcome.
What are p-finally's main functionalities?
Attaching a finally handler to a promise
This feature allows you to execute code after a promise has been settled, regardless of whether it was fulfilled or rejected. It's particularly useful for cleanup operations.
const pFinally = require('p-finally');
const promise = new Promise((resolve, reject) => {
// Some asynchronous operation
});
pFinally(promise, () => {
// Code to run on promise settlement
});
Other packages similar to p-finally
bluebird
Bluebird is a comprehensive promise library that includes a .finally() method among its wide array of features. Compared to p-finally, Bluebird offers a much broader set of promise-related utilities, but it's also larger in size, which might be an overkill for projects only needing a finally functionality.
q
Q is another promise library that supports a .finally() method. Similar to Bluebird, Q provides a wide range of promise manipulation capabilities. It's more feature-rich than p-finally but also larger, making p-finally a lightweight alternative if the finally functionality is the main requirement.
p-finally 
Promise#finally()
ponyfill - Invoked when the promise is settled regardless of outcome
Useful for cleanup.
Install
$ npm install p-finally
Usage
const pFinally = require('p-finally');
const directory = createTempDirectory();
(async () => {
await pFinally(write(directory), () => {
cleanup(directory);
});
});
API
pFinally(promise, onFinally?)
Returns a Promise
.
onFinally
Type: Function
Note: Throwing or returning a rejected promise will reject promise
with the rejection reason.
Related
- p-try -
Promise.try()
ponyfill - Starts a promise chain
- More…