JavaScript
Async Await
Async / Await is syntactic sugar over promises that makes asynchronous code readable and linear, while maintaining the benefits of
Promiseand theEvent Loop.
Main Idea
asyncandawaitsimplify working with promises, allowing you to write asynchronous code in a synchronous style.- The
asynckeyword before a function automatically makes it return aPromise. - The
awaitkeyword pauses function execution until the promise is settled (fulfilledorrejected).
How It Works
async function getUserData() {
try {
const response = await fetch('/api/user');
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
}
}awaitcan be used only inside anasyncfunction.- When
await promiseis executed, the interpreter pauses the function, releasing the thread for other tasks (via the Event Loop). - After the promise is resolved, execution continues with the received value.
- If the promise was rejected, an exception is generated, which can be caught via
try...catch.
Behavior and Microtasks
- Every
awaitaccess creates a microtask. - After pausing the function, the execution of other microtasks continues until the promise is completed.
async/awaitdoes not block the thread — it simply splits execution into phases.- If there is an error in
await, it is passed to the nearestcatch.
Sequential and Parallel Calls
Sequential execution (slower):
await fetchData1();
await fetchData2();
await fetchData3();Parallel execution (more optimal):
const [a, b, c] = await Promise.all([fetchData1(), fetchData2(), fetchData3()]);Key Ideas
asyncguarantees that the function always returns aPromise.awaitmakes the code readable and step-by-step, simplifying the handling of asynchronous operations.- Allows using
try...catchinstead of.then()/.catch(). - Behind the scenes is the same mechanism of promises and the microtask queue of the Event Loop.
- Combined with
Promise.allandPromise.allSettledfor optimizing parallel operations.