How to fetch an array of URLs with promise.all with JavaScript?

Estimated read time 2 min read

To fetch an array of URLs using Promise.all in JavaScript, you can use the fetch API to make individual HTTP requests for each URL and create an array of promises. Then you can pass this array of promises to Promise.all to wait for all the promises to resolve or reject. Here’s an example code snippet that demonstrates this:

const urls = ['https://example.com/data1.json', 'https://example.com/data2.json', 'https://example.com/data3.json'];

const promises = urls.map(url => fetch(url)); // create an array of promises

Promise.all(promises)
  .then(responses => {
    // handle the responses from all the requests
    responses.forEach(response => {
      console.log(response.url, response.status);
    });
  })
  .catch(error => {
    // handle any errors that occurred during the requests
    console.error(error);
  });

In this code, we create an array of URLs to fetch, and then use the map function to create an array of promises by calling fetch for each URL. We pass this array of promises to Promise.all, which returns a new promise that resolves with an array of responses when all the promises have resolved or rejects with the first encountered error.

In the then block, we handle the responses by iterating through the array of responses and logging the URL and HTTP status of each response. In the catch block, we handle any errors that occurred during the requests by logging the error to the console.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply