Created
December 24, 2017 13:29
-
-
Save diogoca/7b418cb2103c94bc43421a1212cb9db2 to your computer and use it in GitHub Desktop.
JavaScript Promise examples
This file contains hidden or 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
<script> | |
function getSalary(salary) { | |
return new Promise(resolve => { | |
setTimeout(() => { | |
resolve(salary); | |
}, 500); | |
}); | |
} | |
function errorSalary() { | |
throw 'Wrong salary'; | |
} | |
function reduceBill(salary) { | |
return new Promise(resolve => { | |
setTimeout(() => { | |
resolve(salary - 100); | |
}, 500); | |
}); | |
} | |
function reduceTax(salary) { | |
return new Promise(resolve => { | |
setTimeout(() => { | |
resolve(salary - 100); | |
}, 500); | |
}); | |
} | |
function getSum() { | |
return Promise.all([ | |
getSalary(1000), | |
getSalary(2000), | |
getSalary(3000), | |
]).then(salaries => { | |
return salaries.reduce((prev, cur) => prev + cur, 0); | |
}); | |
} | |
getSalary(1000) | |
.then(salary => reduceBill(salary)) | |
.then(errorSalary) | |
.then(salary => reduceTax(salary)) | |
.then(salary => console.log(salary)) | |
.catch(e => console.log('EE' + e)); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment