What is the difference between promises and async/await in JavaScript?
- Technology:
- JavaScript
- Topics:
- Asynchronous Programming
Quick answer
async/await is syntax built on top of promises that lets you write asynchronous code that reads like synchronous code; under the hood every async function returns a promise.
Detailed explanation
A promise represents a value that will be available later and is in one of three states: pending, fulfilled or rejected. You consume it with .then() and .catch(). async/await lets you pause an async function with await until a promise settles, and handle errors with ordinary try/catch.
They are equivalent in power, but await makes sequential logic and error handling much easier to read. A common mistake is awaiting independent calls one after another. Use Promise.all to run them in parallel.
Example
// promises
fetch("/api/user").then(r => r.json()).then(showUser).catch(handleError);
// async/await
async function load() {
try {
const res = await fetch("/api/user");
showUser(await res.json());
} catch (err) {
handleError(err);
}
}
// run independent calls in parallel
const [user, posts] = await Promise.all([getUser(), getPosts()]);How to explain it in an interview
async/await is syntax on top of promises. An async function always returns a promise, and await pauses that function until a promise settles, so asynchronous code reads top to bottom. Errors are handled with try/catch instead of .catch, and for independent work I still use Promise.all so the requests run in parallel.
Key points
- async functions always return a promise
- await only pauses the async function, not the whole thread
- Use Promise.all for independent work
Common mistakes
- Awaiting independent calls one after another, which makes them sequential. Start them together and await Promise.all.
- Forgetting that await only works inside async functions (or at the top level of ES modules).
- Leaving promises without error handling, which leads to unhandled rejection warnings or crashes in Node.js.
Follow-up questions
- What is the difference between Promise.all, allSettled, race and any?
- What happens if you forget to await a promise?