Handling Async Issues with Async / Await

Handling Async Issues with Async / Await

  • Let’s see how we can apply Async / Await to your .printLetter() program

Example: Using Async / Await to control the execution order of async functions

function printLetter(letter) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log(letter)
      resolve()
     }, Math.floor(Math.random() * 3000))
  })
}


/*
 convert .printAll() to an async / await function
 by prepending 'await' before the function keyword
*/
async function printAll(){
  await printLetter("A")
  await printLetter("B")  
  await printLetter("C")
  await printLetter("D")
}

console.log('Calling printAll function')
printAll()
console.log('End of code')

JS Bin on jsbin.com

  • In the code above, we modify .printAll() by prepending the declaration with async

  • As a result of this change, we can simplify our promise consumption by using await inside the function to call the letters in sequence: "A" -> "B" -> "C" -> "D"

  • Compare this code to the approach we used with the regular Promise syntax and you’ll notice that the async / await syntax is much cleaner and looks like synchronous code