Watch it run
Pick a snippet, then play it or step through. Every step says what just happened.
async function load(ok) { console.log("load starts"); await null; if (!ok) throw new Error("server said no"); return "data";}async function main() { try { console.log("got", await load(true)); console.log("got", await load(false)); } catch (e) { console.log("caught:", e.message); }}main();console.log("sync done");Call stack
What is running right now
Paused functions
Stopped at an await, on that line
Microtask queue
Drained fully after each task
Console0 lines
Nothing has run yet.
Try it yourself
Change the code, predict the order, then run it for real in your browser.
Press Run to see what your code prints, in order.
Runs in this browser, in an isolated frame with no access to this page. console.log, info, warn and error are shown; code runs as a classic script, so use an async function for await.
Check yourself
2 questions. Get them all right to finish this topic.
0 of 2 right so far. Get all two to finish this topic.
Sequential or parallel
Press Run to see what your code prints, in order.
Runs in this browser, in an isolated frame with no access to this page. console.log, info, warn and error are shown; code runs as a classic script, so use an async function for await.
Awaiting in a loop has the same effect: for (const id of ids) await load(id) loads one at a time. That is right when each step needs the previous one, or when you must go easy on a server; otherwise map to promises first and await them together.
Errors
A rejected promise makes await throw, so ordinary try/catch works. One trap: inside try, write return await work() rather than return work(); without the await, the function returns before the promise settles and your catch never sees the failure.
Press Run to see what your code prints, in order.
Runs in this browser, in an isolated frame with no access to this page. console.log, info, warn and error are shown; code runs as a classic script, so use an async function for await.
In ES modules (and in Node's .mjs files) you can also use await at the top level, outside any function.