0

I have an array over I call an API with its value. But I notice that the calling of the API are not in order to the array content. This is my code:

points = [1, 2, 3, 4]
points.forEach(async point => {
  console.log(point);
  const res = await fetch(`${URL}/${point}`, {headers: { ... }})
  console.log(res);
});

It's look like that it doesn't wait the return of the fetch. I tried with Promise.all() but the problem persist. This is the output of my code:

1
2
3
4
Response {} <-- on point 1
Response {} <-- on point 5
Response {} <-- on point 4
Response {} <-- on point 2
Response {} <-- on point 3
th3g3ntl3man
  • 1,926
  • 5
  • 29
  • 50
  • 1
    _"It's look like that it doesn't wait the return of the fetch"_ - this is why you shouldn't use `forEach` with `async-await`. Use the `for-of` loop. – Yousaf Aug 24 '21 at 13:16

1 Answers1

1

You can't do this with forEach I guess.

I would rather use a for of loop instead like

points = [1, 2, 3, 4]
for(const point of points){
  console.log(point);
  const res = await fetch(`${URL}/${point}`, {headers: { ... }})
  console.log(res);
};
PRSHL
  • 1,359
  • 1
  • 11
  • 30