Handling Async Issues with Promises

Handling Async Issues with Promises

  • Let’s revisit our .printLetter() example and use promises

  • First let’s modify our .printLetter() function to return a Promise

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

//... the rest of code below not shown for brevity

Example: Using Promises 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))
  })
}


function printAll(){
  printLetter("A")
    .then(() => printLetter("B"))  
    .then(() => printLetter("C"))
    .then(() => printLetter("D"))
}

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

JS Bin on jsbin.com


Promise Chain

The following code snippet from the example above is referred to as a promise chain:

printLetter("A")
  .then(() => printLetter("B"))  
  .then(() => printLetter("C"))
  .then(() => printLetter("D"))