What is Async/Await?
Async/await is syntactic sugar on top of Promises that makes asynchronous code look and behave more like synchronous code. It's built on Promises and works with any function that returns a Promise.
💡 Key insight
async functions always return a Promise. await pauses the function execution until the Promise resolves.
Async Functions
// This function returns a Promise
async function fetchData() {
return "Data fetched!";
}
fetchData().then(result => console.log(result));
The await Keyword
await can only be used inside async functions. It pauses execution until the Promise resolves.
async function getData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
}
Error Handling with try/catch
async function getData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Failed to fetch:', error);
}
}
Parallel Execution
Use Promise.all() with await for parallel operations.
async function getMultipleData() {
const [data1, data2] = await Promise.all([
fetch('/api/1').then(r => r.json()),
fetch('/api/2').then(r => r.json())
]);
console.log(data1, data2);
}
Common Mistakes
- Using
awaitoutside anasyncfunction - Forgetting to
try/catcherrors in async functions - Running operations sequentially when they could run in parallel
- Assuming
awaitmakes all code async (it only pauses the current function)
Quick Quiz
1. What does the async keyword do?
2. Can await be used outside an async function?
3. How do you handle errors in async/await?
4. What does an async function return?
Summary
asyncfunctions return a Promiseawaitpauses execution until the Promise resolves- Use
try/catchfor error handling - Use
Promise.all()for parallel operations - Async/await makes code more readable than Promise chains
- Always handle errors to prevent uncaught rejections
