Javascript Fundamentals · Promises & Async

Chain promises with then and catch

promise chaining

Chain promises with then and catch

One async step leads to the next: fetch a user, then fetch that user's posts. If you nest each step inside the callback of the last, the code marches off the right edge and the failure handling scatters across it.

.then does more than attach a callback — it returns a new promise. Whatever your callback returns becomes that promise's value. Return a plain value and the next .then receives it; return another promise and the chain waits for it before continuing. That is how you sequence asynchronous steps without nesting:

getUser(id)
  .then((user) => getPosts(user.id))
  .then((posts) => posts.length);

If any step rejects — or your callback throws — the remaining .then callbacks are skipped and the rejection travels down the chain. A single .catch at the end receives it, and whatever .catch returns resolves the chain instead:

load(id)
  .then(parse)
  .catch(() => fallback);

Because .catch returns a promise too, a recovered chain fulfils normally; leave it off and the rejection reaches the caller.

Export loadPosts from index.js. Your job is to chain the two async steps and recover from any failure with one .catch.

Challenge

Two async steps run in sequence, and if either one fails you want a fallback rather than a crash. Chain them so the second waits for the first, and recover in one place.

Export a loadPosts function from index.js. It takes getUser(id) and getPosts(userId), both returning promises, and returns a new function. Calling it with an id must chain the calls with .then — get the user, then that user's posts — and return a Promise of the posts. If either step rejects, a single .catch must recover by resolving with an empty array.

index.js
export function loadPosts(_getUser, _getPosts) {
  return () => Promise.resolve([]);
}

export function render(mount) {
  const button = document.createElement('button');
  button.textContent = 'Load posts';
  const output = document.createElement('p');
  output.textContent = 'idle';

  const getUser = (id) => Promise.resolve(`${id}-user`);
  const getPosts = (userId) => Promise.resolve([`A post by ${userId}`]);
  const load = loadPosts(getUser, getPosts);

  button.addEventListener('click', () => {
    load('ada').then((posts) => {
      output.textContent = posts.join(', ');
    });
  });

  mount.append(button, output);
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.