async/await and Error Handling
Write async functions with the await keyword, wrap awaited calls in try/catch blocks, and understand how async/await is syntactic sugar over Promises.
What Is async/await?
async/await is syntactic sugar over Promises. An async function always returns a Promise. The await keyword pauses the function until the awaited Promise settles. Code looks synchronous but runs asynchronously.
async Function
Add the async keyword before a function declaration or expression. The function now implicitly wraps its return value in a Promise.
async function fetchUser(id) {
// implicitly returns a Promise
return { id, name: 'Alice' };
}
// Equivalent to:
function fetchUser(id) {
return Promise.resolve({ id, name: 'Alice' });
}All lessons in this course
- The Event Loop: Call Stack Queue Microtasks
- Callbacks and Callback Hell
- Promises: then catch finally Promise.all
- async/await and Error Handling