Promises vs async/await
Both handle asynchronous operations - async/await is syntactic sugar built on top of Promises.
Promise
js
function getUser(id) {
return fetch(`/api/users/${id}`)
.then(res => res.json())
.then(user => {
return fetch(`/api/posts/${user.id}`);
})
.then(res => res.json())
.catch(err => console.error(err));
}async/await - same logic, readable code
js
async function getUser(id) {
try {
const res = await fetch(`/api/users/${id}`);
const user = await res.json();
const postsRes = await fetch(`/api/posts/${user.id}`);
return await postsRes.json();
} catch (err) {
console.error(err);
}
}Promise states
| State | Description |
|---|---|
pending | Initial state - not yet settled |
fulfilled | Operation completed successfully |
rejected | Operation failed |
Parallel execution
js
// sequential - slow (waits for each)
const user = await getUser();
const posts = await getPosts();
// parallel - fast (runs simultaneously)
const [user, posts] = await Promise.all([getUser(), getPosts()]);Other Promise methods
js
Promise.allSettled([...]) // waits for all, even if some reject
Promise.race([...]) // resolves/rejects with the first settled
Promise.any([...]) // resolves with the first fulfilledUse
async/awaitfor readability. Use raw Promises when composing withPromise.all,Promise.race, or building utilities.
updated
did you know it?