JavaScript Promise.any (original) (raw)

Summary: in this tutorial, you’ll learn how to use the JavaScript Promise.any() method to compose promises.

Introduction to JavaScript Promise.any() method

The Promise.any() method accepts a list of Promise objects as an iterable object:

Promise.any(iterable);Code language: JavaScript (javascript)

If one of the promises in the iterable object is fulfilled, the Promise.any() returns a single promise that resolves to a value which is the result of the fulfilled promise:

In this diagram:

The Promise.any() returns a promise that is fulfilled with any first fulfilled promise even if some promises in the iterable object are rejected:

In this diagram:

If all promises in the iterable object are rejected or if the iterable object is empty, the Promise.any() return a promise that is rejected with an AggregateError containing all the rejection reasons. The AggregateError is a subclass of Error.

In this diagram:

JavaScript Promise.any() examples

Let’s take some examples of using the Promise.any() method.

1) All promises fulfilled example

The following example demonstrates the Promise.any() method with all promises fulfilled:

`const p1 = new Promise((resolve, reject) => { setTimeout(() => { console.log('Promise 1 fulfilled'); resolve(1); }, 1000); });

const p2 = new Promise((resolve, reject) => { setTimeout(() => { console.log('Promise 2 fulfilled'); resolve(2); }, 2000); });

const p = Promise.any([p1, p2]); p.then((value) => { console.log('Returned Promise'); console.log(value); }); `Code language: JavaScript (javascript)

Output:

Promise 1 fulfilled Returned Promise 1 Promise 2 fulfilledCode language: JavaScript (javascript)

How it works.

2) One promise rejected example

The following example uses the Promise.any() method with a list of promises that have a rejected promise:

`const p1 = new Promise((resolve, reject) => { setTimeout(() => { console.log('Promise 1 rejected'); reject('error'); }, 1000); });

const p2 = new Promise((resolve, reject) => { setTimeout(() => { console.log('Promise 2 fulfilled'); resolve(2); }, 2000); });

const p = Promise.any([p1, p2]); p.then((value) => { console.log('Returned Promise'); console.log(value); }); `Code language: JavaScript (javascript)

Output:

Promise 1 rejected Promise 2 fulfilled Returned Promise 2Code language: JavaScript (javascript)

In this example, the Promise.any() ignores the rejected promise. When the p2 resolves with the value 2, the Promise.any() returns a promise that resolves to the same value as the result of the p2.

3) All promises rejected example

The following example demonstrates how to use the Promise.any() method with all promises rejected:

`const p1 = new Promise((resolve, reject) => { setTimeout(() => { console.log('Promise 1 rejected'); reject('error1'); }, 1000); });

const p2 = new Promise((resolve, reject) => { setTimeout(() => { console.log('Promise 2 rejected'); reject('error2'); }, 2000); });

const p = Promise.any([p1, p2]); p.catch((e) => { console.log('Returned Promise'); console.log(e, e.errors); }); `Code language: JavaScript (javascript)

Output:

Promise 1 rejected Promise 2 rejected Returned Promise [AggregateError: All promises were rejected] [ 'error1', 'error2' ]Code language: JavaScript (javascript)

In this example, both p1 and p2 were rejected with the string error1 and error2. Therefore, the Promise.any() method was rejected with an AggregateError object that has the errors property containing all the errors of the rejected promises.

When to use the JavaScript Promise.any() method

In practice, you use the Promise.any() to return the first fulfilled promise. Once a promise is fulfilled, the Promise.any() method does not wait for other promises to be complete. In other words, the Promise.any() short circuits after a promise is fulfilled.

For example, you have a resource served by two or more content delivery networks (CDN). To dynamically load the first available resource, you can use the Promise.any() method.

The following example uses the Promise.any() method to fetch two images and display the first available image.

The index.html file

`

JavaScript Promise.any() Demo `Code language: JavaScript (javascript)

The app.js file

`` function getImageBlob(url) { return fetch(url).then((response) => { if (!response.ok) { throw new Error(HTTP status: ${response.status}); } return response.blob(); }); }

let cat = getImageBlob( 'https://upload.wikimedia.org/wikipedia/commons/4/43/Siberian_black_tabby_blotched_cat_03.jpg' ); let dog = getImageBlob( 'https://upload.wikimedia.org/wikipedia/commons/a/af/Golden_retriever_eating_pigs_foot.jpg' );

Promise.any([cat, dog]) .then((data) => { let objectURL = URL.createObjectURL(data); let image = document.createElement('img'); image.src = objectURL; document.body.appendChild(image); }) .catch((e) => { console.log(e.message); }); ``Code language: JavaScript (javascript)

How it works.

Summary

Quiz

Was this tutorial helpful ?