Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
</body>
</html>
 
function getSuperheroes() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
       // comment out to simulate reject()
       /* resolve([
        { name: "Captain Marvel", team: "Avengers" },
        { name: "Batman", team: "Justice League"},
        { name: "Jean Grey", team: "X-Men"},
        { name: "Domino", team: "X-Force"}
      ]) */
      // reject promise
      reject("Oh no!!! An error occurred while fetching heroes.")
    }, 3000)
  });
}
function printHeroes(heroes) {
  heroes.forEach((hero) => {
    console.log(`name: ${hero.name}, team: ${hero.team}`)
  })
}
async function fetchHeroes() {
  /*
    use `try..catch` to catch any errors that occur
    during our asynchronous operation
 */
  try {
    const fetchedHeroes = await getSuperheroes()
    printHeroes(fetchedHeroes)
  } catch (e) {
    console.log(e)
  }
}
console.log("Calling fetchHeroes()")
fetchHeroes()
console.log("end of the code")
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x