promise-any-ponyfill

`Promise.any` ponyfill.

Usage no npm install needed!

<script type="module">
  import promiseAnyPonyfill from 'https://cdn.skypack.dev/promise-any-ponyfill';
</script>

README

promise-any-ponyfill

Build Status BrowserStack Status

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 an AggregateError, a new subclass of Error that groups together individual errors. Essentially, this method is the opposite of Promise.all().

Install

npm install promise-any-ponyfill --save

Usage

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 Promise if the iterable passed is empty.
  • An asynchronously resolved Promise if the iterable passed contains no promises.
  • A pending Promise in 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

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ć