What is p-any?
The p-any package is a utility for handling multiple promises in JavaScript. It returns a promise that is fulfilled when any of the input promises are fulfilled, or rejected if all of the input promises are rejected.
What are p-any's main functionalities?
Basic Usage
This feature demonstrates the basic usage of p-any. It takes an array of promises and returns a promise that resolves as soon as the first promise in the array resolves.
const pAny = require('p-any');
const promise1 = Promise.resolve('First');
const promise2 = new Promise((resolve) => setTimeout(resolve, 100, 'Second'));
const promise3 = new Promise((resolve, reject) => setTimeout(reject, 50, 'Third'));
pAny([promise1, promise2, promise3]).then(value => {
console.log(value); // 'First'
});
Handling Rejections
This feature demonstrates how p-any handles rejections. If all input promises are rejected, p-any returns an AggregateError.
const pAny = require('p-any');
const promise1 = new Promise((resolve, reject) => setTimeout(reject, 100, 'First'));
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 200, 'Second'));
const promise3 = new Promise((resolve, reject) => setTimeout(reject, 300, 'Third'));
pAny([promise1, promise2, promise3]).catch(error => {
console.log(error); // AggregateError: All promises were rejected
});
Other packages similar to p-any
promise-any
The promise-any package provides similar functionality to p-any. It also returns a promise that resolves as soon as any of the input promises resolve, or rejects if all input promises are rejected. The main difference is that promise-any is a polyfill for the Promise.any method introduced in ES2021.
bluebird
Bluebird is a fully-featured promise library that includes a method called Bluebird.any, which provides similar functionality to p-any. Bluebird offers additional features and optimizations for working with promises, making it a more comprehensive solution for promise management.
p-any
Wait for any promise to be fulfilled
Useful when you need the fastest promise.
You probably want this instead of Promise.race()
. Reason.
Install
$ npm install --save p-any
Usage
Checks 3 websites and logs the fastest.
const got = require('got');
const pAny = require('p-any');
pAny([
got.head('github.com').then(() => 'github'),
got.head('google.com').then(() => 'google'),
got.head('twitter.com').then(() => 'twitter'),
]).then(first => {
console.log(first);
});
API
pAny(input)
Returns a Promise
that is fulfilled when any promise from input
is fulfilled. If all the input
promises reject, it will reject with an AggregateError
error.
input
Type: Iterable<Promise|any>
pAny.AggregateError
Exposed for instance checking.
Related
- p-some - Wait for a specified number of promises to be fulfilled
- More…
License
MIT © Sindre Sorhus