zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Javascript] Await a JavaScript Promise in an async Function with the await Operator

JavaScriptasync in The with an Function Promise
2023-09-14 09:00:49 时间

The await operator is used to wait for a promise to settle. It pauses the execution of an async function until the promise is either fulfilled or rejected.

 

const API_URL = "https://starwars.egghead.training/";

const output = document.getElementById("output");
const spinner = document.getElementById("spinner");

async function queryAPI(endpoint) {
  const response = await fetch(API_URL + endpoint);
  if (response.ok) {
    return response.json();
  }
  throw Error("Unsuccessful response");
}

async function main() {
  try {
    const [films, planets, species] = await Promise.all([
      queryAPI("films"),
      queryAPI("planets"),
      queryAPI("species")
    ]);
    output.innerText =
      `${films.length} films, ` +
      `${planets.length} planets, ` +
      `${species.length} species`;
  } catch (error) {
    console.warn(error);
    output.innerText = ":(";
  } finally {
    spinner.remove();
  }
}

main();