Promises
MediumIn plain terms
A Promise is JavaScript's way of handling asynchronous operations—things that take time, like fetching data from a server or reading a file. When you start such an operation, you get back a Promise that starts in the "pending" state. When the operation finishes, the Promise becomes "fulfilled" (success) or "rejected" (error).
You use .then() to run code when the Promise succeeds, .catch() when it fails, and .finally() for cleanup in both cases. Promises can be chained, so you can avoid the nested "callback hell" of deeply indented code. Most modern async work in JavaScript uses Promises.
What you need to know
- •pending, fulfilled, rejected
- •then, catch, finally
- •Chaining
Try it yourself
Copy the code below and run it in your browser console or a code editor:
const p = new Promise((resolve, reject) => {
setTimeout(() => resolve('Done'), 1000);
});
p.then(value => console.log(value))
.catch(err => console.error(err))
.finally(() => console.log('Cleanup'));
fetch('/api/data')
.then(r => r.json())
.then(data => console.log(data))
.catch(err => console.error(err));Why this matters
Promises are the basis of async in JS. You will be asked to use fetch, chain then/catch, or convert callback-based code to Promises. Event loop and microtasks sometimes come up.
How it connects
Promises replace callback hell; async/await is syntax on top of Promises. Fetch returns a Promise. Understanding Promises helps with error handling (catch) and with the event loop (microtask queue).
Interview focus
Be ready to explain these; they come up often in JS interviews.
- ▸Three states: pending, fulfilled, rejected. then/catch/finally; chaining.
- ▸Promise constructor: resolve/reject; wrap callbacks with new Promise.
- ▸Microtasks: Promise callbacks run in microtask queue; order vs setTimeout.
Learn more
Dive deeper with these trusted resources: