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
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')
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"))