Skip to content

Instantly share code, notes, and snippets.

@diogoca
Created December 24, 2017 13:29
Show Gist options
  • Select an option

  • Save diogoca/7b418cb2103c94bc43421a1212cb9db2 to your computer and use it in GitHub Desktop.

Select an option

Save diogoca/7b418cb2103c94bc43421a1212cb9db2 to your computer and use it in GitHub Desktop.

Revisions

  1. diogoca created this gist Dec 24, 2017.
    48 changes: 48 additions & 0 deletions promise.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    <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>