Async/await is the modern way to handle asynchronous operations in JavaScript. It makes your code cleaner and easier to understand.
1. Understanding Promises First
Before diving into async/await, you need to understand Promises:
// A Promise represents a future value
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve('Done!'), 1000);
});
promise.then(result => console.log(result));
2. The async Keyword
The async keyword makes a function return a Promise:
async function greet() {
return 'Hello!';
}
// Same as:
function greet() {
return Promise.resolve('Hello!');
}
3. The await Keyword
Use await to pause execution until a Promise resolves:
async function fetchUser() {
const response = await fetch('/api/user');
const user = await response.json();
return user;
}
Key Point
You can only use await inside an async function!
4. Error Handling
Use try/catch for error handling:
async function fetchData() {
try {
const response = await fetch('/api/data');
return await response.json();
} catch (error) {
console.error('Failed:', error);
throw error;
}
}
5. Parallel Execution
Use Promise.all for parallel requests:
async function fetchAll() {
const [users, posts] = await Promise.all([
fetch('/api/users').then(r => r.json()),
fetch('/api/posts').then(r => r.json())
]);
return { users, posts };
}