Last active
January 26, 2018 21:16
-
-
Save AkyunaAkish/3f5fd3cddb5ba7451c942ec7950ae120 to your computer and use it in GitHub Desktop.
Flat-Chained Promise Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function asyncFunction(bool) { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
if(bool) { | |
resolve('Promise resolved after .5 of a second'); | |
} else { | |
reject('Promise rejected after .5 of a second'); | |
} | |
}, 500); | |
}); | |
} | |
// Promise flat-chain to avoid nesting | |
// FYI: returning a function call that | |
// returns a Promise in a .then will pass | |
// the unresolved promise down to the next | |
// .then in the chain, and the callback function | |
// in the next .then will only run once the passed | |
// promise has resolved. | |
// (this can be done with synchronous values too(data other than Promises)) | |
asyncFunction(true).then(result => asyncFunction(result)) | |
.then(secondResult => asyncFunction(secondResult)) | |
.then(thirdResult => asyncFunction(thirdResult)) | |
.then(fourthResult => { | |
console.log('Reached the end of the promise flat-chain: ', fourthResult); | |
}) | |
.catch(err => { | |
console.log(`If any Promise in the chain fails/rejects, | |
the rejected Promise will bubble/pass | |
it's result to this .catch: `, err); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment