Search code examples
javascriptes6-promisepromise.all

Console.log as HTTP requests are happening in promise array


I am making an HTTP request to an API for as many entries there are on an array.

What I am trying to do is console.log each time is doing a request but I am unable to make the promise log it as it happens, it'll wait for all to be done and then it logs it all at once.

const data = ['one','two']
    
// This simulates the API response I have no control here
const mockAPI = (timeout) => {
  return new Promise((resolve, reject) => setTimeout(() => resolve(), timeout))
}

let counter = 0

// For each entry in the array
const promises = data.map(() => {
  return new Promise(async (resolve, reject) => {
    // Keep track of how many request are we up to
    counter++
    // Log it
    console.log(counter)
    // Make the call to the API
    await mockAPI(3000)
    // Do something with the data from API...
    resolve()
  })
})
// I collect the results of all promises to processes it later on
const result = Promise.all(promises) 

What I would like is to log:

1

Wait three seconds - as per example obviously as long as the API takes then:

2

Solution

  • Try with for loop, await for each request and console.log When you do with Promise.All, all fetches/async tasks run parallel (based on browser resources)

    Update: Added the way to accumulate the results

    // This simulates the API response I have no control here
    const mockAPI = (timeout) => {
      const rand = Math.floor(Math.random() * 100);
      return new Promise((resolve, reject) =>
        setTimeout(() => resolve(rand), timeout)
      );
    };
    
    (async function () {
      const results = [];
      let counter = 0;
      for (let i = 0; i < 3; i++) {
        console.log(counter++);
        const res = await mockAPI(3000);
        results.push(res);
      }
    
      console.log(results);
    })();