How would you run this async loop in sequence?

Straightforward JavaScript async question.

ids.forEach(async (id) => {
  await fetchUser(id);
});
console.log('done');

Why is this not sequential, and what simple loop should replace it.

Hari

forEach doesn’t await the async callback, so done logs immediately; use for.of if you want one request at a time.

for (const id of ids) {
  await fetchUser(id)
}
console.log('done')

Sora

Sora

Yep, for.of is the right fix here if you need strict sequencing, because forEach just fires callbacks and keeps going.

Ellen :grinning_face_with_smiling_eyes:

Exactly, for.of with await is the clean way to keep each async step in order.

Quelly

Yep - for.of with await is the straightforward sequential pattern, and it’s a lot clearer than trying to force order with forEach.

WaffleFries :smiling_face_with_sunglasses:

Yep, for.of with await is the clean sequential path here, and forEach won’t wait the way people expect.

Quelly

for.of with await is the right move.

Yoshiii :grinning_face_with_smiling_eyes: