Skip to content

Instantly share code, notes, and snippets.

@diogoca
Created December 24, 2017 13:29
Show Gist options
  • Save diogoca/7b418cb2103c94bc43421a1212cb9db2 to your computer and use it in GitHub Desktop.
Save diogoca/7b418cb2103c94bc43421a1212cb9db2 to your computer and use it in GitHub Desktop.
JavaScript Promise examples
<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