Upgrade to Pro — share decks privately, control downloads, hide ads and more …

meet.js Katowice - ES6 Promises 101

meet.js Katowice - ES6 Promises 101

Szymon Nowak

March 09, 2016
Tweet

More Decks by Szymon Nowak

Other Decks in Programming

Transcript

  1. sum(1, 5, (x) => { multiply(x, 3, (y) => {

    subtract(y, 5, (z) => { console.log('The result is', z); }); }); });
  2. sum(1, 5) .then((x) => multiply(x, 3)) .then((x) => subtract(x, 5))

    .then((x) => { console.log('The result is', x) });
  3. promise = new Promise((resolve, reject) => { // do something

    async... if (success) { resolve(result); } else reject(reason); } });
  4. promise = new Promise((resolve, reject) => { setTimeout(() => resolve(42),

    2000); }); function onResolve(result) { console.log(`Resolved with ${result}`); } promise.then(onResolve);
  5. promise = new Promise((resolve, reject) => { setTimeout(() => resolve(42),

    2000); }); function onResolve(result) { return result + 10; } promise .then(onResolve) .then(doSomething) .then(doSomethingElse);
  6. sum(1, 5, (x) => { multiply(x, 3, (y) => {

    subtract(y, 5, (z) => { console.log('The result is', z); }); }); });
  7. sum(1, 5) .then((x) => multiply(x, 3)) .then((x) => subtract(x, 5))

    .then((x) => { console.log('The result is', x) });
  8. function authenticate() { if (user) { return Promise.resolve(user); } return

    fetchUser(); } authenticate().then((user) => ...)
  9. new Promise((resolve, reject) => { throw new Error(‘bazinga!’); }); //

    exception inside promises // are translated to rejections