JavaScript · Level 3 Async

async / await & Promise.all

Start several API calls together and wait for all of them with Promise.all, instead of waiting for each one in turn.

  • async functions return Promises
  • await pauses until a Promise settles
  • Promise.all runs in parallel and keeps order

await pauses an async function until a Promise settles. Trap: await inside a for loop waits for each request before starting the next. Start them all, then await Promise.all(...).

async function getAll(urls, get) {
  const pending = urls.map((u) => get(u));  // all start now
  return await Promise.all(pending);        // results in input order
}

Write async function loadAll(ids, fetchUser): call fetchUser(id) for every id in parallel (each resolves to { name }) and return the names in the order of ids, e.g. ["user1", "user2", "user3"].

solution.js
Test Suites Pending
Output