Skip to content
Happy Programming Guide
Start learning
JavaScript

JavaScript Promises Explained With Examples

A promise is a value that is not ready yet. How to create one, chain them, handle errors, run several at once, and why async/await is promises with nicer syntax.

A Sony camera with a large black lens is positioned on a wooden table, alongside a white keyboard and a white

A promise is an object that stands in for a value you do not have yet: the response to a request, the contents of a file, the result of a timer. It starts pending and later settles as either fulfilled with a value or rejected with an error. Everything asynchronous in modern JavaScript hands you one, and async/await is a nicer way of writing the same promise code. This article builds the idea up from a single example to the patterns you use every day.

A promise in one example#

JavaScript
const response = fetch('/api/user/1');       // a Promise, pending right now
console.log(response);                         // Promise { <pending> }

response.then(res => {
  console.log(res.status);                     // runs later, when the response arrives
});

console.log('this line runs first');

fetch returns immediately with a promise. The code continues. When the response arrives, the promise fulfils and the function passed to then runs with the value. That is the whole mechanism: register what to do with the value, get on with other things.

The three states#

  • Pending: not yet settled.
  • Fulfilled: settled with a value; then handlers run.
  • Rejected: settled with a reason, usually an Error; catch handlers run.

A promise settles once and never changes. Attaching a handler to an already-settled promise runs it immediately (on the next tick), which is why you can call then whenever you like.

Chaining#

JavaScript
fetch('/api/user/1')
  .then(res => res.json())                  // returns a promise: the next then waits for it
  .then(user => user.name.toUpperCase())    // returns a plain value: passed straight on
  .then(name => console.log(name))
  .catch(err => console.error('Failed:', err.message));

Every then returns a new promise for whatever its handler returns. Return a value and the next handler gets it; return a promise and the chain waits for it to settle. That is what turns nested callbacks into a flat sequence. One catch at the end handles a rejection from any step above it.

Error handling#

JavaScript
fetch('/api/user/1')
  .then(res => {
    if (!res.ok) throw new Error('HTTP ' + res.status);   // turn a bad status into a rejection
    return res.json();
  })
  .then(user => render(user))
  .catch(err => showError(err))
  .finally(() => hideSpinner());

Throwing inside a handler rejects the chain, so catch catches both network failures and errors you raise deliberately. finally runs either way, for cleanup. Note that fetch only rejects on network failure; a 404 or 500 is a fulfilled promise with a bad status, which is why the ok check is there.

A rejection with no catch anywhere becomes an unhandled rejection, logged by the browser or Node. Every chain should end in a catch, or be awaited inside a try.

Creating a promise#

Most of the time you consume promises that APIs give you. Creating one is for wrapping something callback-based:

JavaScript
function wait(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

function loadImage(src) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => resolve(img);
    img.onerror = () => reject(new Error('Could not load ' + src));
    img.src = src;
  });
}

await wait(500);
const img = await loadImage('/logo.png');

The function you pass runs immediately and receives resolve and reject. Call one of them when the outcome is known. Node’s util.promisify does this automatically for standard callback functions.

Several at once#

JavaScript
// All must succeed; results in order; rejects on the first failure
const [user, posts] = await Promise.all([fetchUser(id), fetchPosts(id)]);

// Wait for all, whatever happens; inspect each outcome
const results = await Promise.allSettled([fetchUser(id), fetchPosts(id)]);
results.forEach(r => r.status === 'fulfilled' ? use(r.value) : log(r.reason));

// First to settle, fulfilled or rejected - typically for timeouts
const data = await Promise.race([fetchUser(id), wait(5000).then(() => { throw new Error('timeout'); })]);

// First to fulfil; rejects only if all reject
const fastest = await Promise.any([mirror1(), mirror2(), mirror3()]);

Promise.all is the one you will use most, and the mistake to avoid is awaiting in sequence when the requests are independent:

JavaScript
const user = await fetchUser(id);       // one after the other: slow
const posts = await fetchPosts(id);

const [u, p] = await Promise.all([fetchUser(id), fetchPosts(id)]);   // together: fast

async/await is the same thing#

JavaScript
async function showUser(id) {
  try {
    const res = await fetch('/api/user/' + id);
    if (!res.ok) throw new Error('HTTP ' + res.status);
    const user = await res.json();
    render(user);
  } catch (err) {
    showError(err);
  } finally {
    hideSpinner();
  }
}

Identical behaviour to the chain above, written as ordinary sequential code. await pauses the function until the promise settles and gives you the value, or throws the rejection. An async function always returns a promise, whatever you return from it, which is why callers can await it or chain then on it.

The syntax hides the promises but does not remove them, and two mistakes come from forgetting that:

JavaScript
async function save(data) {
  api.post('/save', data);          // forgot await: the function returns before the save finishes
}

async function load() {
  const items = getItems();         // forgot await: items is a Promise, not an array
  items.map(...);                   // TypeError: items.map is not a function
}

Microtasks and ordering#

JavaScript
console.log(1);
Promise.resolve().then(() => console.log(2));
setTimeout(() => console.log(3), 0);
console.log(4);
// 1, 4, 2, 3

Promise handlers run as microtasks, after the current code finishes and before timers. Knowing that a then handler never runs synchronously, even for an already-settled promise, explains a whole class of “why did this print in that order” questions.

Questions people ask#

Is a promise the same as a callback?

A promise is an object that lets you attach callbacks after the fact and chain them. It solves the nesting and error-propagation problems of raw callbacks.

Can a promise be cancelled?

Not directly. Use an AbortController with fetch and other APIs that support it; the promise then rejects with an abort error.

What does Promise.resolve do?

Wraps a value in an already-fulfilled promise, or returns the promise unchanged if given one. Useful for treating sync and async values the same way.

Why does my catch not catch an error thrown inside setTimeout?

Because the timer callback runs outside the promise chain. Wrap the timer in a promise, as in the wait example, so its outcome is part of the chain.

Where to go next#

Handling fetch errors properly in JavaScriptRead next

Keep reading

JavaScript

JavaScript Security

XSS, CSRF, dependency risk, token storage and prototype pollution — the JavaScript vulnerabilities that matter, in the browser and in Node.

5 min read

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *