Skip to content

Instantly share code, notes, and snippets.

@AkyunaAkish
Last active January 26, 2018 21:16
Show Gist options
  • Save AkyunaAkish/3f5fd3cddb5ba7451c942ec7950ae120 to your computer and use it in GitHub Desktop.
Save AkyunaAkish/3f5fd3cddb5ba7451c942ec7950ae120 to your computer and use it in GitHub Desktop.
Flat-Chained Promise Example
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