Promises in JavaScript: how to create and consume them
Promise constructor, resolve reject, then catch finally, Promise states, chaining promises, error propagation, Promise.resolve Promise.reject, returning from then
A Promise Represents a Future Value
A Promise is an object that represents the eventual result of an async operation. It starts in the pending state and settles to either fulfilled (success) or rejected (failure). Once settled, its state and value never change. Promises replaced callback hell as the standard pattern for async JavaScript.
Creating a Promise
function fetchUser(id) {
return new Promise((resolve, reject) => {
if (id <= 0) {
reject(new Error("Invalid ID"));
return;
}
setTimeout(() => resolve({ id, name: "Ana" }), 500);
});
}
Consuming with .then/.catch/.finally
fetchUser(1)
.then(user => {
console.log(user.name); // "Ana"
return user.id; // value passed to next .then
})
.then(id => console.log("ID:", id))
.catch(err => console.error(err.message))
.finally(() => console.log("Done — runs regardless"));
Error Propagation
If any .then callback throws or returns a rejected Promise, execution jumps to the nearest .catch. A single .catch at the end of a chain handles errors from any step above it.
Most Common Bug
Forgetting to return inside a .then callback means the next handler receives undefined instead of the transformed value. Every .then that transforms data must explicitly return it.
