promise-any-ponyfill v1.0.0
promise-any-ponyfill
Promise.any()takes an iterable of Promise objects and, as soon as one of the promises in the iterable fulfills, returns a single promise that resolves with the value from that promise. If no promises in the iterable fulfill (if all of the given promises are rejected), then the returned promise is rejected with anAggregateError, a new subclass ofErrorthat groups together individual errors. Essentially, this method is the opposite ofPromise.all().
Install
npm install promise-any-ponyfill --saveUsage
import pAny from 'promise-any-ponyfill';
(async () => {
try {
const first = await pAny([
Promise.resolve('becky'),
Promise.resolve('roxy'),
Promise.resolve('sadie')
]);
// Any of the promises was fulfilled.
console.log(first);
// → 'becky'
} catch (error) {
// All of the promises were rejected.
console.log(error);
}
})();You can use named export preferNative if you wish to use native
implementation if it’s available. In all other cases, ponyfill will be used.
Beware of
caveats!
API
any(iterable)
Returns:
- An already rejected
Promiseif the iterable passed is empty. - An asynchronously resolved
Promiseif the iterable passed contains no promises. - A pending
Promisein all other cases. This returned promise is then resolved/rejected asynchronously (as soon as the stack is empty) when any of the promises in the given iterable resolve, or if all the promises have rejected.
iterable
An iterable object, such as an Array.
Browser support
Tested in Chrome 90, Firefox 88, Internet Explorer 11 and should work in all modern browsers (support based on Browserslist configuration).
Assumes Promise and AggregateError are polyfilled or available in global
context.
Acknowledgments
- Proposed implementation and description on StackOverflow
- Proposed implementatio on TC39 feature repository
Related
Test
Test suite is taken and modified from es-shims test suite.
For automated tests, run npm run test:automated (append :watch for watcher
support).
License
MIT © Ivan Nikolić
4 years ago