1

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
Álvaro
  • 2,255
  • 1
  • 22
  • 48

1 Answers1

2

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);
})();
Siva K V
  • 10,561
  • 2
  • 16
  • 29
  • Thanks, although this works in that it waits for each, I have no way to collect results as I was with `const result = Promise.all(promises) ` – Álvaro Feb 11 '21 at 12:48
  • @Álvaro you can use map() to map the promises to a new array and then use Promise.all() – Aalexander Feb 11 '21 at 12:49
  • @Aalexander, thanks. would you mind illustrating that on a response? I tried the map on my question but did not work. – Álvaro Feb 11 '21 at 12:50
  • 1
    @Álvaro, I just updated the snippet to handle the results accumalation. You can try some thing like this. (I just added random value as each result) – Siva K V Feb 11 '21 at 12:53
  • @sivako, thanks, I will try this. What I am doing on the real app is processing the results of the API requests on the promises then accumulating then on a array and after the calls have been made I used a reduce on the results to further process that data – Álvaro Feb 11 '21 at 12:56
  • It does indeed work, I had to refactor a bit cause I was using map, btw I am using this in node so I guess I would have to make that for loop `async` somehow, in any case I going to accept the answer – Álvaro Feb 11 '21 at 13:15