JavaScript async/await: Write Async Code That Reads Clearly
Promise chains work, but long ones are hard to read. async and await let you write the same logic top to bottom, as if each step simply waited for the previous one. Under the hood it is still promises.
async functions
Putting async before a function changes two things. It always returns a promise: a returned value becomes the fulfillment value, and a thrown error becomes a rejection. That is why the example's first line reports that main() returns a promise. And it allows await inside its body.
await
await somePromise pauses this function until the promise settles, then gives you the fulfilled value, or throws the rejection as an error. Other code keeps running in the meantime, which is why "main() returns a Promise" prints before anything inside main that comes after the first await. In modern browsers and in JavaScript modules you can also use await at the top level, outside any function.
Expected output
main() returns a Promise: true got Book #3 error: book 99 not found [1, 2, 4] in parallel: true main finished
Errors with try...catch
Because a rejected await throws, ordinary try...catch handles asynchronous errors. In the example, fetchBook(99) rejects, and the catch block prints the message while main carries on. Without a try, the rejection would make main()'s promise reject; the caller could still catch it with .catch().
Sequential versus parallel
Each await waits before the next line starts. Three independent calls written one after another therefore take three times as long. When the steps do not depend on each other, start them all and await them together: await Promise.all([fetchBook(1), fetchBook(2), fetchBook(4)]). In the example, three 20-millisecond lookups finish in roughly 20 milliseconds, not 60. Results come back in the order you listed them.
Practical tips
fetch()in the browser returns a promise, so you typically writeconst res = await fetch(url); const data = await res.json();.- Always handle errors at some level: either with
try...catchinside, or.catch()where you call the function. forEachdoes not wait for async callbacks. Usefor...ofwithawaitfor sequential work orPromise.allwithmapfor parallel work.
Common mistakes
- Forgetting
await, so you get a pending promise instead of the value. - Using
awaitinside a non-async function, which is a syntax error. - Awaiting independent tasks one by one when they could run in parallel.
Summary
asyncfunctions always return promises.awaitpauses the function until a promise settles and returns its value.- Use
try...catcharoundawaitto handle rejections. - Run independent work with
Promise.allto save time.
Quiz: async and await