Async/Await Patterns
`async`/`await` is modern JavaScript syntax that makes asynchronous code look and read like synchronous code, while still being non-blocking under the hood.
An `async` function always returns a Promise, and `await` pauses execution inside that function until the awaited Promise settles.
Basic usage
Mark a function `async`, then use `await` before any Promise-returning expression to get its resolved value directly.
Error handling
Wrap awaited code in `try/catch` to handle rejected Promises cleanly, similar to handling synchronous exceptions.
async function getUser() {
const res = await fetch('https://api.example.com/user/1');
const data = await res.json();
return data;
}
getUser().then(user => console.log(user));{ id: 1, name: 'Ada' }await pauses until each Promise resolves, making the flow read top-to-bottom.
async function safeCall() {
try {
const data = await mightFail();
console.log(data);
} catch (err) {
console.error('Failed:', err.message);
}
}Failed: Something went wrongtry/catch handles rejected Promises inside async functions.
Key points
- async functions always return a Promise.
- await pauses execution until a Promise settles.
- try/catch handles errors in async/await code.
- async/await is syntactic sugar over Promises.
