Skip to content
javascript questions

JavaScript · 6 of 10middle~1 min

What are Promises and how do they differ from async/await?

#async#core

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

StateDescription
pendingInitial state - not yet settled
fulfilledOperation completed successfully
rejectedOperation 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 fulfilled

Use async/await for readability. Use raw Promises when composing with Promise.all, Promise.race, or building utilities.

updated

did you know it?

related questions