iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Promises

A Promise is an object representing the eventual result of an asynchronous operation. It moves through three states: pendingfulfilled (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

pending fulfilled (value) rejected (error) resolve(v) reject(e)
Fig 1. A promise resolves once and stays in that state.

Combinators

HelperResolves 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')]);

Test yourself

Q1. A promise can be…
Q2. Which combinator NEVER rejects?
Q3. After `.then()` returns a value, the chain…

Discussion

Loading…