JavaScript Interview Question: Promises vs async/await
Short answer: a promise represents a value that will be available later; it's pending, then fulfilled or rejected. async/await is syntax on top of promises: an async function always returns a promise, and await pauses the function until a promise settles.
Same logic, two styles
// Promise chain
function loadUser(id) {
return fetch(`/api/users/${id}`)
.then((res) => res.json())
.catch((err) => { console.error(err); return null; });
}
// async/await
async function loadUser(id) {
try {
const res = await fetch(`/api/users/${id}`);
return await res.json();
} catch (err) {
console.error(err);
return null;
}
}
Key facts interviewers look for
- An
asyncfunction returns a promise even if youreturn 5. throwinside anasyncfunction rejects its promise.awaitonly pauses that function, not the whole program.- Unhandled rejections are errors; always
catchsomewhere.
Sequential vs parallel
// Sequential: ~2 seconds if each takes 1 second
const a = await getA();
const b = await getB();
// Parallel: ~1 second
const [a, b] = await Promise.all([getA(), getB()]);
Common mistakes
array.forEach(async (x) => await save(x))doesn't wait for anything. Usefor...ofwithawait, orPromise.all(array.map(...)).- Forgetting
await, so you get a promise instead of a value (and errors escape your try/catch). - Awaiting independent calls one by one when they could run in parallel.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.