JS Promises
A Promise is an object representing the eventual result of an asynchronous operation. It moves through three states: pending → fulfilled (with a value) or rejected (with an error).
Creating & consuming
JS
// Usually you don't create them by hand — APIs return them.
const wait = (ms) => new Promise(resolve => setTimeout(resolve, ms));
await wait(500); // pause without blocking the page
// Consuming with .then / .catch / .finally
wait(500)
.then(() => console.log("done"))
.catch(e => console.error(e))
.finally(() => console.log("always runs"));
Promise state diagram
Combinators
| Helper | Resolves when… | Rejects when… |
|---|---|---|
Promise.all([p1, p2]) | All resolve. | Any rejects (fail-fast). |
Promise.allSettled([…]) | All settle. | Never. Inspect each {status, value | reason}. |
Promise.race([…]) | First settles. | If the first to settle rejects. |
Promise.any([…]) | First to fulfil. | Only if all reject (with AggregateError). |
Tip: Always return from inside
.then if you're chaining. fetch(…).then(r => r.json()) works because .json() returns a promise that the chain awaits.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Promises!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Run two fetches in parallel and wait for both.
const [a, b] = await Promise.
([fetch('/a'), fetch('/b')]);
Three letters — fail-fast combinator.
Discussion
Loading…