JavaScript · Lesson 11

Promises and async/await

How JavaScript handles work that finishes later, from callbacks to promises to async/await, plus chaining, error handling, running things in sequence or in parallel, timeouts, retries and the mistakes everyone makes once.

16 min read

In short

  • A promise is pending, then fulfilled or rejected, once
  • then returns a new promise: return values and promises
  • async functions return promises; await throws rejections
  • Start independent work first, then Promise.all
  • Await, return, or catch every promise

A lot of the work a program does finishes later: a network request, a file read, a timer, a database query. JavaScript doesn't stop and wait for it. It starts the work, carries on, and runs some of your code when the result arrives. This lesson is about how you write that "some of your code" so it stays readable and so errors don't get lost.

There are three layers, and you'll meet all of them in real codebases:

  1. Callbacks: you pass a function, and it gets called with the result.
  2. Promises: an object that stands for a result that isn't there yet.
  3. async/await: syntax that lets promise code read top to bottom, like normal code.

Every js snippet below has a ▶ Try button. Predict the output, then run it. The playground waits for pending timers and promises before it stops, like Node does before exiting.

Callbacks, and why we moved on

Before promises, async APIs took a callback. Node's convention is error first: the callback's first argument is an error (or null), the second is the result.

▶ Try
function readConfig(name, callback) {
  setTimeout(() => {
    if (name === 'missing') callback(new Error('no such file: ' + name));
    else callback(null, { name, port: 8080 });
  }, 10);
}

readConfig('app', (err, config) => {
  if (err) return console.log('failed:', err.message);
  console.log('loaded', config.name, 'on port', config.port);
});
console.log('this prints first: readConfig returned straight away');

Callbacks work, but they have real problems once there's more than one step:

  • Nesting. Step two needs step one's result, so it goes inside step one's callback, and so on. Three steps in, the code drifts to the right ("callback hell").
  • Errors at every level. Each callback has to check err and pass it on. Forget once and the error vanishes. A try/catch around the call doesn't help, because the callback runs later, after the try block has finished.
  • Trust. You hand your function to someone else's code. It might call it twice, never, or sometimes synchronously and sometimes later. Each of those causes subtle bugs.
  • Combining is manual. "Run these three at once and tell me when all are done" needs counters and flags.

Promises fix all four.

What a promise is

A promise is an object that represents the eventual result of some work. It is always in one of three states:

StateMeaning
pendingthe work hasn't finished yet
fulfilledit finished with a value
rejectedit failed with a reason (usually an Error)

Fulfilled and rejected are both called settled. A promise settles once. After that, its state and value never change, and later calls to resolve or reject are ignored.

▶ Try
const p = new Promise((resolve, reject) => {
  console.log('1. the executor runs right away');
  resolve('first');
  resolve('second'); // ignored: already settled
  reject(new Error('nope')); // ignored too
});

p.then((value) => console.log('3. then got:', value));
console.log('2. end of script');

Three facts from that snippet that people get wrong:

  • The function you pass to new Promise (the executor) runs synchronously, immediately.
  • resolve doesn't call your then callback. It settles the promise and queues the callbacks.
  • A then callback never runs synchronously, even when the promise is already settled. It runs after the current code finishes. The Event Loop topic explains exactly when.

Most of the time you don't call new Promise yourself. fetch, fs/promises and most libraries already return promises. You use new Promise to wrap an older callback or timer API, like this:

▶ Try
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

sleep(20).then(() => console.log('20 ms later'));

Promise.resolve(value) and Promise.reject(error) make already-settled promises. They're handy in tests and when a function must return a promise but already has the answer (a cache hit, for example).

then returns a new promise

This is the most important rule about promises: then returns a new promise, and what your callback returns decides how that new promise settles.

Your callback...The promise returned by then...
returns a plain valuefulfils with that value
returns a promisefollows it: settles the same way, when it does
throwsrejects with the thrown error
returns nothingfulfils with undefined

That's what makes chaining work. Each step can return a value or start more async work, and the next step waits for it:

▶ Try
const getUser = (id) => Promise.resolve({ id, name: 'Ann', teamId: 7 });
const getTeam = (id) => new Promise((resolve) => setTimeout(() => resolve({ id, name: 'Platform' }), 10));

getUser(1)
  .then((user) => getTeam(user.teamId)) // returns a promise: the chain waits for it
  .then((team) => team.name.toUpperCase()) // returns a value: passed straight on
  .then((name) => console.log('team:', name));

The chain stays flat, no matter how many steps it has. The classic bug is forgetting to return:

▶ Try
const save = (x) => new Promise((resolve) => setTimeout(() => resolve('saved ' + x), 10));

Promise.resolve('draft')
  .then((x) => {
    save(x); // no return: the chain doesn't wait, and the result is lost
  })
  .then((result) => console.log('result:', result));

It prints result: undefined, because the callback returned nothing. With braces, you need an explicit return. With a one-line arrow function such as (x) => save(x), the return is implicit.

Errors flow down the chain

A rejection skips every then success callback until it reaches a catch (or a then with a second argument). That's the async version of an exception unwinding to the nearest try/catch:

▶ Try
Promise.resolve(1)
  .then((n) => {
    throw new Error('step 2 failed');
  })
  .then(() => console.log('skipped'))
  .then(() => console.log('also skipped'))
  .catch((e) => {
    console.log('caught:', e.message);
    return 'fallback'; // catch returns normally: the chain recovers
  })
  .then((v) => console.log('carries on with', v))
  .finally(() => console.log('finally runs either way'));

Rules worth knowing:

  • catch(fn) is then(undefined, fn). It returns a new promise too. If the handler returns, the chain is back on the success path. If it throws (or rethrows), the chain stays rejected.
  • Where you put the catch matters. A catch in the middle handles errors from the steps above it and lets the rest continue. A catch at the end handles everything.
  • then(onOk, onError) is not the same as then(onOk).catch(onError). In the first form, onError does not see errors thrown by onOk.
  • finally(fn) runs on both paths, gets no argument, and passes the original result or error through. Use it for cleanup such as hiding a spinner.
  • A thrown error inside any callback becomes a rejection. You don't need Promise.reject there: just throw.

async/await

async/await is promises with nicer syntax. Two rules cover most of it:

  1. An async function always returns a promise. return x fulfils it with x. throw e rejects it. Calling an async function never throws: errors arrive as rejections.
  2. await p pauses the function until p settles, then gives you the value, or throws the rejection reason at that line. You can only use it inside an async function (or at the top level of a module).
▶ Try
const getUser = async (id) => ({ id, name: 'Ann', teamId: 7 });
const getTeam = async (id) => {
  if (id !== 7) throw new Error('team not found');
  return { id, name: 'Platform' };
};

async function teamNameFor(userId) {
  const user = await getUser(userId);
  const team = await getTeam(user.teamId);
  return team.name;
}

teamNameFor(1).then((name) => console.log('team:', name));

It reads like synchronous code, and normal try/catch works again, because await turns a rejection into a thrown error at that line:

▶ Try
async function loadProfile() {
  throw new Error('503 Service Unavailable');
}

async function showProfile() {
  try {
    const profile = await loadProfile();
    console.log('profile', profile);
  } catch (e) {
    console.log('could not load profile:', e.message);
  } finally {
    console.log('hide spinner');
  }
}

showProfile();

await works on any value. On a plain value, it still pauses until the current code has finished, then continues with that value. An async function runs synchronously until its first await, and the caller only gets control back at that point.

return vs return await

Inside a try block, return somePromise leaves the function before the promise settles, so the catch never sees its rejection. return await somePromise waits inside the try:

▶ Try
const fail = async () => {
  throw new Error('boom');
};

async function withoutAwait() {
  try {
    return fail(); // the try block is already over when this rejects
  } catch {
    return 'caught';
  }
}

async function withAwait() {
  try {
    return await fail(); // the rejection is thrown here, inside the try
  } catch {
    return 'caught';
  }
}

withoutAwait().catch((e) => console.log('withoutAwait rejected:', e.message));
withAwait().then((v) => console.log('withAwait:', v));

Outside a try, return p and return await p behave the same, so most style guides only ask for return await inside try.

Sequential or parallel

await waits. If each step needs the previous result, that's what you want. If the steps are independent, awaiting them one by one wastes time. Start the work first, then wait for all of it:

▶ Try
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));

async function main() {
  let t = Date.now();
  const a = await wait(50, 'a'); // 50 ms
  const b = await wait(50, 'b'); // then another 50 ms
  console.log('sequential', a, b, '~' + Math.round((Date.now() - t) / 50) * 50, 'ms');

  t = Date.now();
  const [c, d] = await Promise.all([wait(50, 'c'), wait(50, 'd')]); // both started at once
  console.log('parallel  ', c, d, '~' + Math.round((Date.now() - t) / 50) * 50, 'ms');
}
main();

The key point: calling an async function starts the work. await doesn't start anything, it only waits. So const p1 = load(1); const p2 = load(2); already runs both at once, and you can await them afterwards. (If you do that, await both soon, or use Promise.all. A promise that rejects while nobody is waiting for it yet can be reported as unhandled.)

The combinators

FunctionFulfils whenRejects whenUse it for
Promise.all(ps)all fulfil, with an array of values in input orderany rejects (the first rejection)independent work you need all of
Promise.allSettled(ps)all settle, with { status, value } / { status, reason } objectsneverbatches where partial success is fine
Promise.race(ps)the first to settle fulfilsthe first to settle rejectstimeouts
Promise.any(ps)the first to fulfilall reject, with an AggregateErrorthe fastest of several mirrors
▶ Try
const ok = (ms, v) => new Promise((resolve) => setTimeout(() => resolve(v), ms));
const fail = (ms, msg) => new Promise((_, reject) => setTimeout(() => reject(new Error(msg)), ms));

async function main() {
  console.log('all:', await Promise.all([ok(20, 'a'), 'plain values work too', ok(10, 'b')]));

  const results = await Promise.allSettled([ok(10, 'a'), fail(5, 'down')]);
  console.log('allSettled:', results.map((r) => r.status + ':' + (r.value ?? r.reason.message)).join(', '));

  console.log('race:', await Promise.race([ok(30, 'slow'), ok(5, 'fast')]));

  console.log('any:', await Promise.any([fail(5, 'mirror 1 down'), ok(15, 'mirror 2')]));

  try {
    await Promise.all([ok(10, 'a'), fail(5, 'b failed')]);
  } catch (e) {
    console.log('all failed fast:', e.message);
  }
}
main();

Results always come back in input order, not in finishing order. And none of these cancel the losers: when Promise.all rejects, the other operations keep running, you've only stopped waiting for them. To actually stop work, pass an AbortSignal (below).

Timeouts and cancellation

A promise has no built-in timeout. The usual helper races the work against a timer, and the detail that separates a good one from a bad one is clearing the timer when the work wins:

▶ Try
function withTimeout(promise, ms) {
  let timer;
  const timeout = new Promise((_, reject) => {
    timer = setTimeout(() => reject(new Error(`timed out after ${ms} ms`)), ms);
  });
  return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}

const slow = new Promise((resolve) => setTimeout(() => resolve('done'), 100));
withTimeout(slow, 20).catch((e) => console.log(e.message));
withTimeout(Promise.resolve('fast'), 1000).then((v) => console.log(v, '(and no timer left behind)'));

Timing out only stops the waiting. The request is still running. To stop the work itself, the standard tool is AbortController: you pass its signal to the work (fetch(url, { signal }) takes one), and calling abort() makes that work stop and reject:

▶ Try
const controller = new AbortController();
const { signal } = controller;

function slowJob(signal) {
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => resolve('finished'), 500);
    signal.addEventListener('abort', () => {
      clearTimeout(timer);
      reject(signal.reason);
    });
  });
}

slowJob(signal).then(console.log, (e) => console.log('stopped:', e.message));
setTimeout(() => controller.abort(new Error('user left the page')), 10);

AbortSignal.timeout(ms) gives you a signal that aborts itself, so fetch(url, { signal: AbortSignal.timeout(5000) }) is a timeout that really cancels the request.

Retry with backoff

Networks fail now and then. A retry loop with await is short, and waiting longer after each failure (exponential backoff) gives a struggling service room to recover:

▶ Try
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function retry(fn, { attempts = 3, delayMs = 10 } = {}) {
  for (let attempt = 1; ; attempt++) {
    try {
      return await fn(attempt); // return await: a rejection is caught below
    } catch (e) {
      if (attempt >= attempts) throw e;
      console.log(`attempt ${attempt} failed (${e.message}), waiting ${delayMs} ms`);
      await sleep(delayMs);
      delayMs *= 2;
    }
  }
}

let calls = 0;
retry(async () => {
  calls++;
  if (calls < 3) throw new Error('503');
  return 'ok on attempt ' + calls;
}).then(console.log);

Only retry errors that can succeed next time (timeouts, 503, 429), not a 400 Bad Request. And only retry operations that are safe to repeat.

promisify: from callbacks to promises

To use an old callback API with await, wrap it once. The wrapper calls the original with an extra callback that resolves or rejects:

▶ Try
function promisify(fn) {
  return function (...args) {
    return new Promise((resolve, reject) => {
      fn.call(this, ...args, (err, value) => (err ? reject(err) : resolve(value)));
    });
  };
}

function readConfig(name, callback) {
  setTimeout(() => (name ? callback(null, { name }) : callback(new Error('name required'))), 5);
}

const readConfigAsync = promisify(readConfig);

async function main() {
  console.log(await readConfigAsync('app'));
  try {
    await readConfigAsync('');
  } catch (e) {
    console.log('rejected:', e.message);
  }
}
main();

Node ships this as util.promisify, and most Node APIs also have a promise version (fs/promises, timers/promises). The first exercise builds it.

Mistakes everyone makes once

1. The forgotten await. Without await, you get a promise, not a value. It often doesn't crash, it just does the wrong thing:

▶ Try
async function isAdmin(userId) {
  return userId === 1;
}

async function check() {
  if (isAdmin(2)) console.log('without await: a promise is always truthy, so user 2 gets in');
  if (await isAdmin(2)) console.log('never printed');
  else console.log('with await: user 2 is not an admin');
}
check();

2. async callbacks inside forEach. forEach ignores the promises your callback returns, so nothing waits for them:

▶ Try
const save = (n) => new Promise((resolve) => setTimeout(() => resolve(n), 10));

async function saveAll(items) {
  const saved = [];
  items.forEach(async (n) => {
    saved.push(await save(n));
  });
  console.log('forEach: saved', saved.length, 'of', items.length); // 0: nothing waited

  const results = await Promise.all(items.map((n) => save(n))); // parallel, and waited for
  console.log('map + Promise.all: saved', results.length);

  for (const n of items) await save(n); // sequential, one at a time
  console.log('for...of with await: done in order');
}
saveAll([1, 2, 3]);

Use for...of with await for one at a time, or map plus Promise.all for all at once. The same applies to filter, some and reduce with async callbacks: they don't wait.

3. Unhandled rejections. A promise that rejects with no handler attached is an unhandled rejection. Browsers log it to the console. Node (since version 15) crashes the process by default. Every promise should end up awaited, returned, or given a catch. A promise nobody handles is called a floating promise; the no-floating-promises lint rule finds them in TypeScript code.

4. Mixing then and await. await fetchUser().then(u => u.name) works, but mixing styles makes it easy to drop a return or put a catch in the wrong place. Inside an async function, prefer await all the way down. Keep then for small one-liners at the edges.

5. Wrapping a promise in new Promise. If you already have a promise, chain it. Wrapping it (new Promise((resolve) => api().then(resolve))) loses rejections, because nobody calls reject. And never pass an async function as the executor: an error thrown in it doesn't reject your promise, which stays pending forever, and the error turns into an unhandled rejection instead.

6. Expecting results in finishing order. Promise.all keeps input order. If you need them as they finish, push into an array inside each then.

Coming from C# or TypeScript

Side note
  • A Promise is like a Task: hot, already running when you get it. Promise.all is Task.WhenAll. Task.WhenAny is Promise.race (the first to finish, success or not). Promise.any waits for the first success, which .NET has no single method for.
  • There's no thread pool. Awaiting doesn't free a thread for other requests, because there's only one thread. It lets the event loop run other callbacks while you wait.
  • There's no CancellationToken parameter built into everything. The JavaScript equivalent is an AbortSignal, and you pass it explicitly.
  • A floating promise is like async void: errors escape and nobody awaits completion.
  • No ConfigureAwait, no deadlocks from .Result: you can't block on a promise at all. If you need the value, you await it.
  • TypeScript adds Promise<T> types but no runtime behaviour. Everything here applies to TypeScript exactly as written.

In real codebases

Side note
  • Frontend data loading: async functions with try/catch/finally for loading and error states, Promise.all for independent requests, and an AbortController per screen so leaving the page cancels its requests. React Query and SWR wrap exactly this, plus caching and retries.
  • Backend handlers: Express 5, Fastify, Hono and Nest all accept async handlers and turn a rejection into a 500 response. Express 4 does not, which is a classic source of hanging requests.
  • Batch jobs: Promise.allSettled to report which items failed, and a concurrency limit (p-limit, p-map) so 5,000 items don't become 5,000 simultaneous requests.
  • Resilience: timeouts on every outbound call (AbortSignal.timeout), retries with backoff and jitter for 429 and 503, and a circuit breaker in front of flaky dependencies.
  • Lint rules catch most mistakes in this lesson: no-floating-promises, no-misused-promises (async callbacks where a sync one is expected) and require-await.

The exercises

  1. promisify (easy): wrap a callback API so it returns promises.
  2. Load a profile page (easy): one step that must come first, then two in parallel.
  3. all and allSettled by hand (medium): rebuild the two combinators.
  4. Fix the async bugs (medium): a forgotten await, an async forEach and a try that doesn't catch.
  5. A timeout that cancels (medium): withTimeout with an AbortSignal and no leftover timers.
  6. withRetry (medium): turn any async function into one that retries with exponential backoff.
  7. A concurrency limiter (hard): run at most N tasks at once, the way p-limit does.
  8. Hedged requests (hard): ask a backup when the first server is slow, keep the first success.

Practise this lesson

In the app: a short video, 8 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.

Open in the app