← JavaScript

Advanced · 3 of 11 · 23 min read

Promises

The three states, what then really returns, the four combinators, and how async/await maps onto all of it.

  • Promises
  • async / await

A promise is an object representing a value that is not available yet. That it is an object is the point: unlike a callback, you can return it, store it, pass it around and combine it with others.

The three states

const pending = new Promise(() => {});                       // never settles
const fulfilled = Promise.resolve(42);                       // already fulfilled
const rejected = Promise.reject(new Error('nope'));          // already rejected

rejected.catch(() => {}); // handled, so no unhandled-rejection warning

fulfilled.then((v) => console.log('value', v)); // value 42
State Means Reached by
pending not finished the initial state
fulfilled finished with a value resolve(value)
rejected finished with a reason reject(reason), or a throw inside the executor

“Settled” means fulfilled or rejected. A settled promise never changes again — the second resolve below does nothing:

const once = new Promise((resolve) => {
  resolve('first');
  resolve('second'); // ignored
});
once.then(console.log); // "first"

Creating one

The constructor takes an executor that runs synchronously, and hands you the two functions that settle the promise:

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

wait(50, 'done').then(console.log); // "done" after 50ms

function mightFail(ok) {
  return new Promise((resolve, reject) => {
    if (ok) resolve('worked');
    else reject(new Error('failed'));
  });
}

mightFail(false).catch((e) => console.log(e.message)); // "failed"

Reject with an Error, not a string: only an Error carries a stack trace.

In most code you do not need the constructor at all — it is for wrapping something that is not promise-based yet:

const readFileAsync = (path, read) =>
  new Promise((resolve, reject) => {
    read(path, (error, data) => (error ? reject(error) : resolve(data)));
  });

then returns a new promise

This is the mechanism behind everything else. Whatever a handler returns becomes the fulfilment value of the promise then returned:

Promise.resolve(1)
  .then((n) => n + 1)          // returns 2 → the next promise fulfils with 2
  .then((n) => n * 10)         // 20
  .then((n) => console.log(n)); // 20, and this one fulfils with undefined

If a handler returns a promise, the chain waits for it and unwraps it — one level of flattening that makes sequencing possible:

const wait = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));

wait(10, 'first')
  .then((v) => {
    console.log(v);         // "first"
    return wait(10, 'second'); // returning a promise defers the next then
  })
  .then((v) => console.log(v)); // "second", 10ms later

Forgetting the return is the classic chain bug: the next handler receives undefined and runs immediately instead of waiting.

Promise.resolve()
  .then(() => {
    wait(10, 'ignored'); // no return — nobody waits for this
  })
  .then((v) => console.log('got', v)); // "got undefined", straight away

Errors travel down the chain

A throw or a rejection skips every then until it finds a catch:

Promise.resolve(1)
  .then(() => {
    throw new Error('boom');
  })
  .then(() => console.log('skipped'))
  .catch((error) => console.log('caught:', error.message)) // caught: boom
  .then(() => console.log('and the chain continues')); // runs — catch recovers

A catch that returns a value recovers, which is how you supply a fallback:

Promise.reject(new Error('offline'))
  .catch(() => 'cached value') // recovered
  .then((v) => console.log(v)); // "cached value"

To re-fail, rethrow:

Promise.reject(new Error('offline'))
  .catch((error) => {
    console.log('logging:', error.message);
    throw error; // still a failure for whoever is downstream
  })
  .catch(() => console.log('final handler')); // logging: offline / final handler

finally runs either way, passes the value through, and takes no arguments:

Promise.resolve('value')
  .finally(() => console.log('cleanup'))
  .then((v) => console.log(v)); // cleanup / value

Place catch after the thens it should cover. .then(a).catch(b).then(c) does not catch an error thrown by c.

A promise chain stepped through: the promise pending, the chain built, the promise fulfilling, a handler throwing, a then being skipped, and catch recovering.
promise ppendingfulfilled: 'A'rejectedthe chain.then(v => v + 'B').then(() => { throw }).then(v => log('skipped')).catch(() => 'recovered').then(v => log(v))Microtask queueConsolerecoveredjoberror

1 wait(100, 'A') returns a promise immediately. It is pending: no value, and nothing scheduled.

2-6 The whole chain is built now, while p is still pending. Five handlers registered, each .then already holding its own new promise, none of them run.

— 100 ms later p fulfils with 'A'. Settling does not call the handler — it puts a job in the microtask queue.

2 The job runs and returns 'AB', which fulfils this link's own promise and queues the next handler.

3 This one throws. The promise it returned is rejected, and the job travelling down the chain is now an error.

4 So this link is skipped. It only has an onFulfilled handler and there is no value to give it — the rejection keeps going.

5 catch runs and returns a value. Returning normally from a catch fulfils the chain again — that is all recovering is.

6 The last handler logs 'recovered'. The chain ended fulfilled even though something threw in the middle of it.

Three things worth watching. The chain is built long before any of it runs (step 2). Settling a promise only ever queues a job, it never calls a handler (step 3). And a rejection travels down the chain skipping every .then until something handles it (steps 5 to 7).

A chain, step by step

Fulfil, transform, throw, skip, recover. Walking it one microtask at a time is the fastest way to see why the order is what it is:

const p = wait(100, 'A');
p.then((v) => v + 'B')
  .then(() => { throw new Error('x'); })
  .then((v) => console.log('skipped'))
  .catch(() => 'recovered')
  .then((v) => console.log(v));

The combinators

Waits for Rejects when Result
Promise.all all to fulfil any rejects, immediately array of values
Promise.allSettled all to settle never array of {status, value | reason}
Promise.race the first to settle the first settles as a rejection that one’s outcome
Promise.any the first to fulfil all reject the first value
const ok = (v, ms = 10) => new Promise((r) => setTimeout(() => r(v), ms));
const bad = (m, ms = 10) => new Promise((_, j) => setTimeout(() => j(new Error(m)), ms));

Promise.all([ok(1), ok(2)]).then(console.log);          // [1, 2]
Promise.all([ok(1), bad('x')]).catch((e) => console.log('all:', e.message)); // all: x

Promise.allSettled([ok(1), bad('x')]).then((results) => {
  console.log(results.map((r) => r.status)); // ["fulfilled", "rejected"]
});

Promise.race([ok('fast', 5), ok('slow', 50)]).then(console.log); // "fast"
Promise.any([bad('a', 5), ok('eventually', 20)]).then(console.log); // "eventually"

all is the one to reach for by default. allSettled when partial success is acceptable and you want to report the failures. race for timeouts. any for redundant sources where the first good answer wins.

A timeout, which is race’s real use:

const withTimeout = (promise, ms) =>
  Promise.race([
    promise,
    new Promise((_, reject) => setTimeout(() => reject(new Error('timed out')), ms)),
  ]);

withTimeout(ok('data', 100), 50).catch((e) => console.log(e.message)); // timed out

async and await

async makes a function return a promise. await pauses inside it until a promise settles, unwrapping the value or throwing the reason.

async function load() {
  return 42; // wrapped automatically
}
console.log(load() instanceof Promise); // true
load().then(console.log);                // 42

async function run() {
  const value = await load();       // 42, not a promise
  console.log(value);
  const bad = await Promise.reject(new Error('oops')).catch((e) => e.message);
  console.log(bad);                 // "oops"
}
run();

The chain and the await version are the same program:

// then-chain
function loadChain(id) {
  return getUser(id)
    .then((user) => getOrders(user.id))
    .then((orders) => orders.length)
    .catch(() => 0);
}

// async/await
async function loadAwait(id) {
  try {
    const user = await getUser(id);
    const orders = await getOrders(user.id);
    return orders.length;
  } catch {
    return 0;
  }
}

try/catch works because await throws the rejection reason — the one place where asynchronous errors behave like synchronous ones.

Sequential versus parallel

The single most common performance bug in modern JavaScript:

const slow = (v) => new Promise((r) => setTimeout(() => r(v), 1000));

async function sequential() {
  const a = await slow('a'); // 1s
  const b = await slow('b'); // another 1s — it only starts now
  const c = await slow('c'); // another 1s
  return [a, b, c];          // ~3 seconds
}

async function parallel() {
  const [a, b, c] = await Promise.all([slow('a'), slow('b'), slow('c')]);
  return [a, b, c];          // ~1 second — all three started together
}

Sequential await is correct when each step needs the previous result. When they are independent, start them all and await the group. The same mistake inside a loop:

async function slowLoop(ids) {
  const out = [];
  for (const id of ids) out.push(await slow(id)); // one at a time
  return out;
}

async function fastLoop(ids) {
  return Promise.all(ids.map((id) => slow(id))); // all at once
}

Note that forEach with an async callback does not wait at all — it returns undefined and the promises escape:

async function broken(ids) {
  ids.forEach(async (id) => {
    await slow(id); // nobody awaits these
  });
  console.log('done'); // logged immediately, before any work finished
}

Use for...of with await for sequential, or Promise.all(map(...)) for parallel. forEach has no place in asynchronous code.

Microtasks: the ordering question

Promise callbacks go to the microtask queue, which is drained completely after the current synchronous work and before any timer:

console.log('1 sync');

setTimeout(() => console.log('5 timeout'), 0);

Promise.resolve().then(() => console.log('3 microtask'));
queueMicrotask(() => console.log('4 microtask'));

console.log('2 sync');
// 1 sync / 2 sync / 3 microtask / 4 microtask / 5 timeout

Both synchronous lines first, then every microtask in order, then the timer. The rule: all microtasks before the next macrotask. The executor body itself is synchronous, which catches people out:

console.log('a');
new Promise((resolve) => {
  console.log('b'); // runs now, not later
  resolve();
}).then(() => console.log('d'));
console.log('c');
// a / b / c / d

Common mistakes

Forgetting to return inside then

Mistake. .then(() => { doAsync(); }). Why it fails. The chain does not wait, so the next handler gets undefined and ordering breaks. What to do instead. return doAsync(), or use an await.

async inside forEach

Mistake. items.forEach(async (i) => { await save(i); }). Why it fails. forEach ignores the returned promises, so the function continues before any save finishes and failures become unhandled rejections. What to do instead. for (const i of items) await save(i) for sequential, or await Promise.all(items.map(save)) for parallel.

Mixing new Promise with an existing promise

Mistake. new Promise((resolve) => fetch(url).then(resolve)). Why it fails. It is redundant, and it drops the rejection path — fetch failing leaves the new promise pending forever. What to do instead. Return the promise you already have. Only use the constructor to wrap a callback-based API.

Check yourself

3 questions from the bank on what you just read. Answering here does not affect your quiz history.

The four promise combinators differ in how they treat a rejection among the inputs.

What does this log?

Code sample
const a = Promise.resolve(1);
const b = Promise.reject(new Error("boom"));
const c = Promise.resolve(3);

Promise.all([a, b, c])
  .then((v) => console.log("then", v))
  .catch((e) => console.log("catch", e.message));

How does Promise.any differ from Promise.race?

An async function does not run entirely out of line — part of it is synchronous.

What does this log?

Code sample
async function run() {
  console.log("1");
  await null;
  console.log("2");
}

run();
console.log("3");
Practise Promises and async / await →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.