Passing values with Promises

Passing values with Promises

  • A common use case when working with asynchronous code is to take the data received from one asynchronous call (output) and use that data as input for another function or action in your program

  • Promises allow developers to easily pass data (or values) between functions


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
*/

function fetchHeroes() {
  /*
   make asynchronous call to .getSuperheroes()
   and use .then() to pass the result from
   .getSuperheroes ("fetchedHeroes")
   so it can be used as a parameter
   for .printHeroes()
 */

 getSuperheroes()
   .then((fetchedHeroes) => {
     printHeroes(fetchedHeroes)
   })
}

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

JS Bin on jsbin.com

  • In the code above, we have two functions .getSuperheroes() which is responsible for asynchronously fetching a list of superheroes and .printHeroes which is responsible for printing the heroes to the console

  • .printHeroes depends on the data from the (asynchronous) .getSuperheroes() function

  • In addition to helping us control the sequence of asynchronous functions, .then() also allows us to “pass” values to other function in the “promise chain”

  • .getSuperheroes returns an array of objects, we use .then() to pass that array of objects as a parameter (fetchedHeroes) to the next function in the promise chain: printHeroes()