01 / 21

Creating & Consuming
Promises

Master asynchronous JavaScript by learning to create Promises with constructors and consume them using .then() and .catch() chains.

JavaScript

What is a Promise?

A Promise is a JavaScript object that represents the eventual completion (or failure) of an asynchronous operation and the resulting value. Think of it like an IOU: the code promises to give you a result later.

The Promise Lifecycle

pending resolve(value) reject(reason) fulfilled rejected .then() .catch() handler handler settled (immutable once resolved or rejected)

Why Do We Need Promises?

Before Promises, JavaScript developers used callbacks for async work. Nesting callbacks inside callbacks created "callback hell": deeply indented, hard-to-read, and error-prone code.

✕ Callback Hell
Deeply nested functions, error handling scattered everywhere, hard to follow the logic flow.
✓ Promises
Flat .then() chains, centralized error handling with .catch(), composable and readable.

The Promise Constructor

You create a new Promise using the Promise constructor. It takes a single function called the executor, which receives two callbacks: resolve and reject.

const myPromise = new Promise((resolve, reject) => { // Do async work here const success = true; if (success) { resolve("Data loaded!"); } else { reject("Something went wrong"); } });

Consuming: .then() and .catch()

Once a Promise exists, you consume it by attaching handlers. .then() handles fulfilled values; .catch() handles rejections.

myPromise .then((value) => { console.log(value); // "Data loaded!" }) .catch((error) => { console.error(error); // "Something went wrong" });

Callbacks vs Promises

Callbacks Promises
Error handling Manual per callback Centralized .catch()
Readability Deeply nested (pyramid) Flat .then() chains
Composability Difficult to combine Promise.all(), .race()
Return values Cannot return from async Chainable return values
Guarantees Callback may fire 0, 1, or 2+ times Settles exactly once

Chaining .then() Calls

Because .then() returns a new Promise, you can chain multiple .then() calls. Each step transforms the data and passes it along.

fetch("/api/user") .then((response) => response.json()) .then((data) => { console.log(data.name); return data.id; }) .then((id) => fetch(`/api/posts/${id}`)) .then((res) => res.json()) .catch((err) => console.error(err));

How the Chain Flows

.then() parse JSON value .then() extract id id .then() fetch posts done If any step throws or rejects: .catch(handler) Success path Error path

How to Apply Promises

1
Identify the async operation: what takes time? (network request, timer, file read, etc.)
2
Wrap it in new Promise(): pass an executor with resolve and reject parameters.
3
Call resolve(value) when the operation succeeds; call reject(reason) when it fails.
4
Consume with .then(): attach a success handler to process the fulfilled value.
5
Always add .catch(): handle errors gracefully at the end of every chain.

Example 1: Coin Flip Promise

function flipCoin() { return new Promise((resolve, reject) => { const flip = Math.random(); if (flip > 0.5) { resolve("Heads!"); } else { reject("Tails — you lose."); } }); } flipCoin() .then((msg) => console.log(msg)) .catch((err) => console.log(err));

Example 2: Delayed Timer

function wait(ms) { return new Promise((resolve) => { setTimeout(() => { resolve(`Waited ${ms}ms`); }, ms); }); } wait(2000) .then((msg) => { console.log(msg); // "Waited 2000ms" return wait(1000); }) .then((msg) => console.log(msg)); // "Waited 2000ms" then "Waited 1000ms"

Example 3: Real-World Fetch

function getUser(id) { return fetch(`/api/users/${id}`) .then((res) => { if (!res.ok) { throw new Error(`HTTP ${res.status}`); } return res.json(); }); } getUser(42) .then((user) => console.log(user.name)) .catch((err) => console.error("Failed:", err));

.finally() and Two-Argument .then()

.finally(callback)
Runs after the Promise settles, regardless of outcome. Perfect for cleanup: hiding spinners, closing connections. The callback receives no arguments.
.then(onFulfill, onReject)
The second argument to .then() is an optional rejection handler. It catches errors from the previous step only, unlike .catch() which catches all upstream errors.
fetch("/api/data") .then((res) => res.json()) .then((data) => render(data)) .catch((err) => showError(err)) .finally(() => hideSpinner());

Common Mistakes

✕ Forgetting to return
Not returning a value (or a Promise) inside .then() breaks the chain: the next .then() receives undefined.
✕ Nesting .then() calls
Writing .then() inside .then() recreates callback hell. Flatten your chain by returning Promises instead.
✕ No .catch() handler
Unhandled Promise rejections crash Node.js and log warnings in browsers. Always end with .catch().

Promise Method Cheatsheet

Method When it runs Receives
.then(fn) On fulfillment The resolved value
.catch(fn) On rejection The rejection reason
.finally(fn) On settlement (either) Nothing (no args)
Promise.resolve(v) Immediately fulfilled Wraps v in a Promise
Promise.reject(r) Immediately rejected Wraps r in a Promise

Question 1 of 5

What are the three possible states of a JavaScript Promise?

Question 2 of 5

What does .then() return?

Question 3 of 5

What gets logged to the console?

Question 4 of 5

What value is logged?

Question 5 of 5

What happens if you forget to add .catch() to a Promise chain that rejects?