async/await is syntactic sugar over Promises. An async function always returns a Promise, and await pauses execution until a Promise resolves, making asynchronous code look and behave more like synchronous code.
async keyword:
await keyword:
Error Handling:
Best Practices:
// Promise-based
function fetchUser(id) {
return fetch(`/api/users/${id}`)
.then(response => response.json())
.then(user => {
console.log(user);
return user;
});
}
// async/await equivalent
async function fetchUser(id) {
const response = await fetch(`/api/users/${id}`);
const user = await response.json();
console.log(user);
return user;
}