- Async/Await is syntactic sugar over Promises.
- Introduced in ES2017 to make async code look synchronous.
- async: Marks a function as asynchronous, so it returns a Promise.
- await: Pauses execution inside an async function until the awaited Promise settles (fulfilled or rejected).
async function fetchData() {
try {
const data = await fetch('https://api.example.com/data');
const json = await data.json();
console.log(json);
} catch (error) {
console.error(error);
} finally {
console.log('Done');
}
}- async function always returns a Promise.
- await:
- Waits for a Promise to resolve.
- Extracts its resolved value.
- If the Promise rejects, await throws the rejection as an error (must handle with try/catch).
- Execution is paused only inside async functions, but other code continues to run (non-blocking).
awaitcan only be used inside anasyncfunction (or at top-level in modules, ES2022+).- If you await a non-Promise value, it just wraps it with
Promise.resolve(value). - Errors are caught with
try/catchinstead of.catch()chaining. - You can await multiple Promises in parallel using
Promise.all()for efficiency.
async function sequential() {
const a = await getData(1);
const b = await getData(2);
console.log(a, b); // Runs one after another
}async function parallel() {
const [a, b] = await Promise.all([getData(1), getData(2)]);
console.log(a, b); // Runs in parallel
}Tip: For independent tasks, prefer parallel to save time.
async function fetchWithErrorHandling() {
try {
const result = await riskyOperation();
console.log(result);
} catch (err) {
console.error('Error:', err);
}
}- What is async/await and why was it introduced?
- What does async do to a function's return value?
- Can you use await outside of an async function? (Only with top-level await in ES2022+)
- How does error handling differ between Promises and async/await?
- How do you run multiple async operations in parallel using async/await?
- What happens if you await a non-Promise value?
- Is async/await blocking? (No, it pauses only the async function, not the whole thread.)
-
Explain the relationship between async/await and the microtask queue.
-
Why is using await inside a loop often a performance issue? How to fix it? (Because it forces sequential execution — fix with Promise.all.)
-
How to implement a timeout with async/await?
async function fetchWithTimeout(ms) {
const timeout = new Promise((_, reject) =>
setTimeout(() => reject('Timeout'), ms)
);
return Promise.race([fetch('url'), timeout]);
}| Feature | Promises (.then/.catch) | Async/Await |
|---|---|---|
| Readability | Can get nested | Looks synchronous |
| Error Handling | .catch() | try/catch |
| Parallel Execution | Promise.all() | Promise.all() |
| Debugging | Stack traces less clear | Stack traces clearer |