JavaScript is single-threaded โ it cannot wait for a server without freezing the page. Async code is how it stays responsive, and async/await is how you write it sanely.
The evolution
// 2010: callback hell
getUser(id, (user) => {
getOrders(user, (orders) => {
getTotal(orders, (total) => { ... });
});
});
// 2020s: async/await
async function show(id) {
try {
const user = await getUser(id);
const orders = await getOrders(user);
const total = await getTotal(orders);
} catch (err) {
console.error(err); // one catch for everything
}
}Parallel, not sequential
// โ 3 seconds if each takes 1s const a = await fetchA(); const b = await fetchB(); const c = await fetchC(); // โ 1 second โ all at once const [a, b, c] = await Promise.all([fetchA(), fetchB(), fetchC()]);
Rules to remember
awaitonly works insideasyncfunctions- An async function always returns a Promise
awaitpauses the function, not the browser
Deep dives: Promises ยท async/await.