Promises: a value that arrives later
Pending, fulfilled, rejected — and the three methods that combine several promises at once.
A promise is a placeholder for a value that is not ready yet. It starts pending, then becomes fulfilled with a value or rejected with an error. Either way, it only settles once.
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done"), 100);
});
promise
.then((value) => console.log(value)) // "done"
.catch((error) => console.error(error))
.finally(() => console.log("cleanup"));Each .then returns a new promise, which is why chains work. Whatever the callback returns becomes the next value. If a callback throws, the chain skips to the nearest .catch.
wait(100, 2)
.then((n) => n * 10) // 20
.then((n) => n + 1) // 21
.then(console.log)
.catch(console.error);Combining promises
// all: fail fast, results in order
await Promise.all([a, b, c]);
// allSettled: always resolves, tells you what worked
const results = await Promise.allSettled([a, b, c]);
// [{ status: "fulfilled", value }, { status: "rejected", reason }]
// race: first to settle wins
await Promise.race([slow, fast]);
// any: first to fulfill wins, ignores rejections
await Promise.any([a, b]);Try it
A promise chain that waits for its own result
Exercises
Checked in your browser · hints and solutions included
Exercise
Write your own delay
Write wait(ms, value) that returns a Promise which resolves with value after ms milliseconds. It must not resolve immediately.
await wait(10, "done") → "done".
Exercise
Load names with a chain
Write loadUserNames() that fetches https://api.example.com/users, reads the JSON, and resolves with an array of just the names — using .then() chaining, not async/await.
Expected: ["Ada", "Grace", "Alan"].