Promise.all with for loop

Promise.all with for loop

The Promise.all method takes an iterable (such as an array) of promises as input, and returns a new promise that resolves when all of the input promises have resolved.

Here's an example of how you might use Promise.all with a for loop:

const urls = [

const promises = [];

for (let i = 0; i < urls.length; i++) {
  const url = urls[i];
  // make an HTTP request for each URL
  const promise = fetch(url)
    // transform the HTTP response into JSON
    .then(response => response.json());
  // add the promise to the promises array

// wait for all the promises in the promises array to resolve
Promise.all(promises).then(results => {
  // all the fetch requests have completed, and the results are in the "results" array

In this example, we are using a for loop to iterate over an array of URLs, and for each URL we are making an HTTP request using the fetch function. The fetch function returns a promise that resolves with the HTTP response. We are then using the then method on the promise to transform the response into JSON.

Finally, we are using the Promise.all method to wait for all of the promises in the promises array to resolve. When all the promises have resolved, the then callback function is called with an array of the resolved values (the JSON objects).

  • Date: