Servers are slow and busy
Real data comes from a server: it takes time, and sometimes it fails. Ask for stock of every dish at the same time with Promise.all, and when the kitchen says *busy*, try again a few times before giving up.
Parallel and retry
async function available() {
const menu = await fetchMenu();
const stock = await Promise.all(menu.map((item) => fetchStock(item.id)));
return menu.filter((item, i) => stock[i].left > 0).map((item) => item.name);
}
async function withRetry(fn, tries) {
let lastError;
for (let i = 0; i < tries; i++) {
try {
return await fn();
} catch (err) {
lastError = err;
}
}
throw lastError;
}
async function placeOrder(order) {
const reply = await withRetry(() => sendOrder(order), 3);
return reply.number;
}