← Back to the exercise

Promises and async/await

The answer to the exercise in Promises and async/await.

Each await on its own line waited for one search before starting the next. Promise.all starts all three at once and waits once. It resolves with the results in the order you listed the promises, so destructuring keeps the same name on the same title.

async function searchName(query) {
  const response = await fetch(
    "https://api.tvmaze.com/search/shows?q=" + query,
  );
  const results = await response.json();
  return results[0].show.name;
}

async function loadAll() {
  const start = Date.now();

  // Was three separate awaits, one after the other.
  const [first, second, third] = await Promise.all([
    searchName("severance"),
    searchName("andor"),
    searchName("the bear"),
  ]);

  console.log("titles:", [first, second, third].join(", "));
  console.log("took about", Date.now() - start, "ms");
}

loadAll();