14. async/await: sugar over promises, and its sharp edges
async/await doesn't change the underlying microtask machinery — it's
syntax that makes promise chains read like synchronous code. An async
function always returns a Promise; await pauses the function (not the
whole program) until the awaited promise settles.
async function loadDashboard(userId) {
try {
const user = await getUser(userId); // pauses here, yields to the event loop
const posts = await getPosts(user.id); // then here
return { user, posts };
} catch (err) {
// catches rejections from EITHER await above — same benefit as .catch()
throw new Error(`Dashboard load failed: ${err.message}`);
}
}
The sharp edge: sequential awaits that don't depend on each other
serialize work that could run concurrently.
// SLOW: each await blocks the next from even starting — total time = sum of both
const user = await getUser(id);
const settings = await getSettings(id); // doesn't need `user` — but waits anyway
// FAST: start both requests immediately, await their results together
const [user, settings] = await Promise.all([getUser(id), getSettings(id)]);