Promises
A Promise is an object representing a value that isn't ready yet: the result of a download, a database query, a timer. It's in one of three states:
- pending: still waiting,
- fulfilled: finished with a value,
- rejected: failed with an error.
Using a promise: then and catch
JavaScript
function wait(ms, value) {
return new Promise((resolve) => setTimeout(() => resolve(value), ms));
}
wait(500, "Data loaded")
.then((result) => console.log(result))
.catch((err) => console.log("Failed:", err.message));
console.log("This prints first: promises don't block.");.then runs when the promise fulfills; .catch runs if it rejects.
Creating a promise
JavaScript
function checkStock(item) {
return new Promise((resolve, reject) => {
setTimeout(() => {
const stock = { keyboard: 5, webcam: 0 };
if (stock[item] > 0) resolve(`${item}: ${stock[item]} in stock`);
else reject(new Error(`${item} is sold out`));
}, 300);
});
}
checkStock("keyboard").then(console.log).catch((e) => console.log(e.message));
checkStock("webcam").then(console.log).catch((e) => console.log(e.message));Call resolve(value) on success and reject(error) on failure.
Chaining
Each .then returns a new promise, so steps chain in order without nesting, fixing the callback pyramid:
JavaScript
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
wait(200)
.then(() => { console.log("step 1"); return wait(200); })
.then(() => { console.log("step 2"); return wait(200); })
.then(() => console.log("step 3"))
.catch((err) => console.log("Something failed:", err))
.finally(() => console.log("cleanup runs either way"));One .catch at the end handles an error from any step.
Running in parallel
JavaScript
const fetchFake = (name, ms) => new Promise((r) => setTimeout(() => r(`${name} (${ms} ms)`), ms));
Promise.all([fetchFake("user", 300), fetchFake("orders", 500), fetchFake("settings", 100)])
.then((results) => console.log("All done:", results));
Promise.race([fetchFake("fast server", 150), fetchFake("slow server", 600)])
.then((winner) => console.log("First back:", winner));Promise.allwaits for all to fulfill, and rejects if any fails.Promise.allSettledwaits for all and reports each success or failure.Promise.racesettles with the first to finish.
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.