try, catch and finally with await
The rejected promise made await throw, so the ordinary catch handled it. finally ran both times. Try the buttons too.
async functions always return a promise, and inside them await pauses that function (not the page) until a promise settles, so async code reads top to bottom with ordinary try...catch; start independent jobs before awaiting them to keep them parallel.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 5 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Rewrite this with async/await and try...catch: getUser().then((u) => getPosts(u.id)).then((p) => console.log(p.length)).catch((e) => console.log("Error:", e.message));
Write async function loadAll(ids, load) that loads every id in parallel and returns an array of results in the same order.
Write async function retry(fn, times) that calls the async function fn up to times times, returning the first success and throwing the last error if all fail.
Explain it without notes
What does an async function return, and what does await do?
Does await block the main thread? Explain what really happens.
How do you handle errors with async/await, and what happens to an uncaught one?
How do you run two independent async jobs in parallel with await, and why is await a(); await b(); slower?
What is top-level await, where can you use it, and what is its cost?
Preview
Console
Nothing logged yet.Expected console output
Loaded: { name: 'Asha', points: 120 }
Finished (ok = true)
Caught: Server said 503
Finished (ok = false)