Passing Values with Async / Await

Passing values with Async / Await

  • Similar to the original Promise syntax, we can easily pass values from one async function to other functions if needed

Example

function getSuperheroes() {
  return new Promise(resolve => {
    setTimeout(() => {
      // send an array of heroes when
      // promise is resolved
      resolve([
        { name: "Captain Marvel", team: "Avengers" },
        { name: "Batman", team: "Justice League"},
        { name: "Jean Grey", team: "X-Men"},
        { name: "Domino", team: "X-Force"}
      ])
    }, 3000)
  });
}

function printHeroes(heroes) {
  heroes.forEach((hero) => {
    console.log(`name: ${hero.name}, team: ${hero.team}`)
  })
}

/*
Declare function with "async" keyword
*/

async function fetchHeroes() {
  // make asynchronous call to .getSuperheroes()
  // wait for the result and then use that
  // result as input for the .printHeroes() function

  const fetchedHeroes = await getSuperheroes()
  printHeroes(fetchedHeroes)
}

console.log("Calling fetchHeroes()")
fetchHeroes()
console.log("end of the code")

JS Bin on jsbin.com