Sometimes, we want to fetch an array of URLs with Promise.all with JavaScript.
In this article, we’ll look at how to fetch an array of URLs with Promise.all with JavaScript.
How to fetch an array of URLs with Promise.all with JavaScript?
To fetch an array of URLs with Promise.all with JavaScript, we call Promise.all with an array of promises.
For instance, we write
const texts = await Promise.all(
urls.map(async (url) => {
const resp = await fetch(url);
return resp.text();
})
);
to call urls.map with an async function that calls fetch and returns the response as the resolve value of the promise returned.
Then we call Promise.all with the array of promises returned by map to make the requests.
Next we get the responses from the texts array which we get from using await on the promise returned by Promise.all.
Conclusion
To fetch an array of URLs with Promise.all with JavaScript, we call Promise.all with an array of promises.