Patterns as words
Lesson 9 Async and concurrency
await in a loop, gather, timeouts and retries
What you'll learn
- Spot await inside a loop and say when running together is faster
- Catch a missing await before it hides a bug
- Know when steps must stay in a row
AI loves to put await inside a loop. It works, it passes the tests, and it makes your page three times slower than it needs to be.
The idea
Async code waits for slow things: the network, the disk, a database. await means pause here until the answer is back. A promise is a not-yet answer. Forget the await and you hold the not-yet answer instead of the answer.
The speed question is: are these waits in a row or together? await inside a loop is one after another. Promise.all starts them all, then waits once. Together is faster, but only when no step needs the result of another.
1async function loadPrices(ids) {2 const prices = [];3 for (const id of ids) {4 const price = await fetchPrice(id);5 prices.push(price);6 }7 return prices;8}910async function loadPricesFast(ids) {11 return Promise.all(ids.map((id) => fetchPrice(id)));12}1314async function refreshAll(ids) {15 const prices = await loadPricesFast(ids);16 await saveCache(prices);17 return prices;18}
- Line 4
awaitinside a loop: each call waits for the one before it. Ten ids means ten waits in a row. Fine when order matters, slow when it doesn't. - Line 11
mapstarts every call first, thenPromise.allwaits once. The results come back in the same order asids. - Line 16 Imagine
saveCache(prices)without itsawait: the function would move on without waiting, and a failure would show up later, far from here. Check every call to an async function.
Take away
awaitin a loop means one at a time;Promise.allmeans all together.- Every call to an async function needs an
await, or a reason why not. - Before running steps together, ask: does any step need another step's result?
Quiz: test yourself
7 questions: a quick quiz, then a review drill. Pick an answer to see why it's right.