Javascript Fundamentals · Promises & Async

Read async code with await

async/await

Read async code with await

A .then chain works, but it reads as a staircase of callbacks. The steps run in one order and you read them in another, so following the flow takes effort.

async / await is syntax for reading promise code top to bottom. Mark a function async and it always returns a promise; put await in front of a promise and the function pauses there until it settles, handing you the resolved value as a plain expression.

The chained version and the awaited version are the same program:

// with .then
function load(id) {
  return getUser(id).then((user) => getPosts(user));
}

// with async / await
async function load(id) {
  const user = await getUser(id);
  const posts = await getPosts(user);
  return posts;
}

The second reads like synchronous code: fetch the user, then fetch the posts, then return. Each await waits for the previous step before running the next line — the order is exactly the order you read. A function that reaches its end returns a promise that fulfils with its return value; a value you return is automatically wrapped.

Export loadProfile from index.js. Your job is to await each step in sequence and return an object with the resolved user and posts.

Challenge

A chain of .then callbacks runs in the right order but reads as a staircase. Reading it top to bottom, the way you read synchronous code, is easier to follow.

Export an async function loadProfile from index.js. It takes two async steps, getUser and getPosts, and awaits them in order: first get the user, then get that user's posts. It returns a promise for an object with the resolved user and posts. The steps must run one after the other, in the order the code is written.

index.js
export async function loadProfile(_getUser, _getPosts) {
  return { user: '', posts: [] };
}

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

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

  button.addEventListener('click', () => {
    loadProfile(getUser, getPosts).then((profile) => {
      output.textContent = `${profile.user}: ${profile.posts.length} post(s)`;
    });
  });

  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.