Consuming Promises
A promise is an object that stands in for a value you do not have yet, such as the result of a network request or a file read. Consuming a promise means attaching code that runs once the promise settles: one handler for success, one for failure, and optionally one that runs either way. You consume promises every time you call fetch(), read a file with fs/promises, or use any library that returns a promise.
The three states and why they matter
Every promise starts out pending. It then moves exactly once to either fulfilled (it has a value) or rejected (it has a reason, usually an Error). After that it never changes again. This is what makes promises predictable: a handler you attach later still receives the same settled result, and a promise can never succeed and then fail.
Reading the result with then, catch and finally
The .then() method takes a callback that receives the fulfilled value. The .catch() method takes a callback that receives the rejection reason. The .finally() method runs a callback with no arguments after either outcome, which is handy for hiding a loading spinner.
fetch('/api/products')
.then(response => {
if (!response.ok) {
throw new Error('Server replied with ' + response.status);
}
return response.json();
})
.then(products => {
console.log('Loaded', products.length, 'products');
})
.catch(error => {
console.error('Could not load products:', error.message);
})
.finally(() => {
document.querySelector('#spinner').hidden = true;
});
How chaining passes values along
Each call to .then() returns a brand new promise. Whatever your callback returns becomes the value of that new promise. If you return a plain value, the next .then() receives it straight away. If you return another promise, as response.json() does above, the chain waits for it and passes along its result. This lets you write a sequence of asynchronous steps as a flat list instead of nesting callbacks inside callbacks.
Throwing inside any .then() callback turns the new promise into a rejected one. The chain then skips every remaining .then() until it reaches a .catch(). That is why one .catch() at the end can handle errors from every step before it.
The mistake of forgetting to return
The most common bug when consuming promises is starting an asynchronous call inside .then() without returning it. The chain does not know about that inner promise, so the next step runs too early and receives undefined. Errors from the inner call also escape your .catch() and show up as "Uncaught (in promise)" warnings in the console.
// Wrong: the inner promise is lost
getUser(id).then(user => {
getOrders(user.id);
}).then(orders => console.log(orders)); // undefined
// Right: return it so the chain waits
getUser(id).then(user => {
return getOrders(user.id);
}).then(orders => console.log(orders));
A related slip is placing .catch() in the middle of a chain. A catch handler that does not rethrow turns the chain back into a fulfilled one, so later .then() callbacks run with whatever the catch returned. Put recovery logic in the middle only when you really want the chain to continue.
Points to remember
- A promise settles once, to either a value or a reason.
- Always return from a
.then()callback when the next step depends on it. - Check
response.okwithfetch(), because HTTP error codes do not reject the promise on their own. - End each chain with
.catch()so no rejection goes unhandled.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.