You Awaited Every Save Inside forEach and the Import Said Done Before Any Had Finished
The import endpoint took a file of price changes, saved each row, and replied with a count. rows.forEach(async (row) => { await savePrice(row); }); return { saved: rows.length }; It read well. There was an await on
The import endpoint
took a file of price changes,
saved each row,
and replied with a count.
rows.forEach(async (row) => {
await savePrice(row);
});
return { saved: rows.length };
It read well.
There was an await
on every save.
It passed review.
It passed the tests,
mostly.
Then the support desk
started hearing a strange story.
The screen said
two hundred prices updated.
The shop still showed
the old ones.
Ten seconds later,
some of them had changed.
And now and then
the whole Node process
fell over in the night
with an unhandled rejection
nobody could tie to a request.
Here is the mechanism.
An async function
returns a promise
the moment it reaches its first await.
forEach calls your function
once per row
and throws the return value away.
It does not wait for it.
It cannot.
It was written
before promises existed,
and it was never taught
what one is.
So the loop started
two hundred saves,
finished in a millisecond,
and the endpoint replied
while every one of them
was still in flight.
The await was real.
It just paused
the little function inside,
not the code around it.
And when a save failed,
its rejection had nobody waiting for it.
Since Node 15
an unhandled rejection
ends the process by default.
That was the crash in the night.
The fix is to choose,
on purpose,
how the saves should run.
One after another:
for (const row of rows) {
await savePrice(row);
}
All at once,
and wait for every one:
await Promise.all(rows.map(savePrice));
The first is slower
and keeps the order.
The second is faster
and can flood the database,
so cap it
if the list can be long.
Either way,
the reply now comes
after the work,
and a failure
comes back to the caller
instead of to the process.
Most linters can catch this.
Turn on the rule
that flags a promise nobody handles.
The lesson is bigger than one method.
An await only waits
inside the function it is written in.
If the caller
does not wait for that function,
nothing waited at all.
– Serguey Asael Shinder
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.