Last active
November 13, 2016 13:21
-
-
Save smks/39d137e8d385c710c9efb03b145ac8aa to your computer and use it in GitHub Desktop.
Example of chaining multiple promises
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
const monthlyRent = 600; | |
const monthlyFoodCosts = 420.5; | |
const monthlyElectricBill = 45; | |
const monthlyGymMemberShip = 38; | |
const monthlySpotifyMemberShip = 15; | |
let costsOutstanding = 1118.5; | |
const payExpense = (expenseAmount) => { | |
return new Promise((resolve, reject) => { | |
if (expenseAmount) { | |
setTimeout(() => { | |
costsOutstanding -= expenseAmount; | |
console.log('Paid! outstanding is: ' + costsOutstanding); | |
resolve(); | |
}, 500); | |
} else { | |
reject('Sorry! Your payment did not go through'); | |
} | |
}); | |
}; | |
const checkIfPaidEverything = () => { | |
if (costsOutstanding > 0) { | |
console.log('You still have ' + calculatedTotal + ' to pay!'); | |
} else { | |
console.log('Everything is paid! Woohoo!'); | |
} | |
}; | |
// Pay one after the other | |
payExpense(monthlyRent) | |
.then(() => {return monthlyFoodCosts;}) | |
.then(payExpense) | |
.then(() => {return monthlyElectricBill;}) | |
.then(payExpense) | |
.then(() => {return monthlyGymMemberShip;}) | |
.then(payExpense) | |
.then(() => {return monthlySpotifyMemberShip;}) | |
.then(payExpense) | |
.then(checkIfPaidEverything) | |
.catch((message) => { | |
console.log(message); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment