Async/Await
How async/await simplifies asynchronous code and how it maps to Promises internally.
Short explanation
async/await lets you write asynchronous code in a synchronous-like style by
awaiting Promises. It's syntactic sugar over Promises but improves readability
and error handling.
Syntax example
async function fetchData() {
try {
const res = await fetch('/api/data');
const data = await res.json();
return data;
} catch (err) {
console.error(err);
}
}
How JS handles it internally
An async function returns a Promise. The runtime pauses the function at each
await until the awaited Promise resolves, then resumes execution. The event
loop and microtask queue are involved in resolving awaited Promises.
FAQ
Q: Are async functions slower than Promises?
A: Slight overhead exists, but the clarity and maintainability usually outweigh performance costs in application code.