Javascript Fundamentals · Promises & Async

Avoid the request waterfall

sequential vs parallel awaits

Avoid the request waterfall

You load a user and that user's posts, but the two requests are independent. Wait for the first to finish before starting the second and the page takes as long as both added together, even though they could have run at once.

Two awaits in a row are sequential: the second does not start until the first finishes. When the two tasks are independent, that is a waterfall — you pay the sum of their times instead of the longer of the two.

// waterfall: ~200ms + ~150ms
const user = await getUser(id);
const posts = await getPosts(id);

// parallel: ~200ms (the slower one)
const [user, posts] = await Promise.all([getUser(id), getPosts(id)]);

The fix is to start every task first, then await them together. Calling each async function produces its promise immediately — the work is already in flight — so you collect the promises and hand them to Promise.all, which fulfils once they all do.

const promises = ids.map((id) => fetchItem(id));
const items = await Promise.all(promises);

ids.map((id) => fetchItem(id)) starts every request in the same tick; await Promise.all(...) then waits for the batch. Reach for the sequential form only when a later step genuinely needs an earlier result.

Export loadAll from index.js. Your job is to start every task before awaiting any of them, so the batch runs in parallel.

Challenge

Independent requests awaited one after another make the page as slow as the sum of their times. Start them together and wait once.

Export an async function loadAll from index.js. It takes an array of task functions, each returning a promise, and returns a promise for an array of their results in input order. Every task must be started before any is awaited, so independent work runs in parallel instead of as a waterfall.

index.js
export async function loadAll(tasks) {
  const results = [];

  for (const task of tasks) {
    results.push(await task());
  }

  return results;
}

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

  button.addEventListener('click', () => {
    loadAll([
      () => new Promise((resolve) => setTimeout(() => resolve('first'), 30)),
      () => new Promise((resolve) => setTimeout(() => resolve('second'), 10)),
    ]).then((results) => {
      output.textContent = results.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.