Dependent async steps
Read sequential asynchronous results where each step depends on the previous one.
JS Puzzles · Const
async functions return promises, and await pauses only the surrounding function. After the awaited promise settles, execution continues asynchronously through the microtask queue, so caller code and other microtasks can run first.
An async function starts running immediately, but await pauses that function and returns control to its caller. Once the awaited promise settles, the suspended continuation is scheduled as a microtask, so statements after await run after currently executing synchronous code and already queued microtasks.
async function name(parameters) { await expression; }An async function always returns a Promise; non-promise return values are wrapped automatically.
async function demo() {
console.log("A");
await Promise.resolve();
console.log("C");
}
demo();
console.log("B");
// A, B, CThe function runs synchronously through the await, then resumes asynchronously; the caller's next synchronous statement runs first.
Read sequential asynchronous results where each step depends on the previous one.
Handle promise failures with ordinary try/catch control flow.
Coordinate several independent operations with Promise.all.
An async function begins synchronously until it reaches await. At that point it yields to its caller, and the code after await resumes in a microtask after the awaited value settles.
Follow-up: What happens with an already-resolved promise? The continuation is still deferred, and other already-scheduled microtasks are processed first.
await pauses the surrounding async function rather than blocking JavaScript globally. Caller code and other independent asynchronous work can continue while the promise is pending.
Follow-up: How can two operations start concurrently? Create both promises before awaiting them, then await Promise.all on the group.
async guarantees that the function returns a promise; ordinary returned values are automatically wrapped as fulfilled promises. A rejection from the awaited promise propagates as an exception unless handled.
Follow-up: How should multiple independent promises be coordinated? Use Promise.all when all results are required, rather than awaiting them one by one.
PromisePromise.allthencatchfinallymicrotasks