Async/Promises
16 min
A Promise represents a value that isn't ready yet — it will either
resolve (succeed, with a value) or reject (fail, with an
error) at some point in the future. async/await is syntax for
working with Promises that reads like ordinary synchronous code:
await somePromise pauses that async function (without blocking
anything else) until the Promise settles, then gives you the resolved
value directly — no .then() callback needed. A rejected Promise
becomes a normal catchable exception at the await point, so
try/catch works on awaited code exactly like it does on
synchronous code.
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function run() {
console.log("start");
await delay(10);
console.log("end");
}
run();
// start
// end (printed ~10ms later)
Between 'start' and 'end', this function is paused (not blocked -- the browser tab stays fully responsive) waiting on a real 10ms timer before continuing to the next line.
Write an `async function getUserName(id)`. First `await new Promise((r) => setTimeout(r, 10))` (a 10ms delay). Then look `id` up in the table `{ 1: "Ada", 2: "Grace" }` and return the name — or the string `"Unknown"` if `id` isn't in the table.
What does `await` actually do to a Promise?
You can write and reason about async/await code, including how awaiting a Promise pauses execution until it settles.