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

JS Promise the right way

JS Promise the right way

Ruby Meetup Ho Chi Minh City, 29th Oct 2016

Nguyễn Nhật Hoàng

October 29, 2016
Tweet

More Decks by Nguyễn Nhật Hoàng

Other Decks in Technology

Transcript

  1. JS PROMISE THE RIGHT WAY @codeaholicguy

  2. CALLBACKS A piece of executable code that is passed as

    an argument to other code, which is expected to call back (execute) the argument at some convenient time.
  3. JQUERY CALLBACK STYLE $(document).ready(function() { $('#button').on('click', function(event) { $.getJSON('/data.json', function(data)

    { console.log(data); }); }); });
  4. NODE.JS CALLBACK STYLE doSomething(params, function(error, result) { if (error) {

    console.error(error.message); } else { console.log(result); } });
  5. CALLBACK HELL getData(function(a) { getMoreData(function(b) { getMoreData(function(c) { getMoreData(function(d) {

    getMoreData(function(e) { / / do something }); }); }); }); });
  6. CALLBACK HELL getData(function(error, a) { if (error) { handleError(error); }

    else { getMoreData(function(error, b) { if (error) { handleError(error); } else { getMoreData(function(error, c) { / / ... }); } }); } });
  7. None
  8. SO, WE DON'T WANT TO BLOCK BUT… > Callback functions

    tend to become difficult to maintain and debug when nested within long lines of code. > Anonymous inline function in a callback can make reading the call stack very tedious.
  9. PROMISE (ES6) > A promise represents the eventual result of

    an asynchronous operation. > A promise must be in one of three states: pending, fulfilled, or rejected.
  10. PROMISE (ES6) const promise = new Promise((resolve, reject) => {

    / / do async stuff resolve('DONE!'); }); promise.then((result) => { console.log(result); / / result will be 'DONE!' });
  11. PROMISE (ES6) const promise = new Promise((resolve, reject) => {

    / / do async stuff reject(new Error('FAIL!')); }); promise .then((result) => { / / does not get called }) .catch((error) => { / / this does! });
  12. PROMISE (ES6) function sleepAndReturn(duration, value) { return new Promise((resolve, reject)

    => { setTimeout(() => (resolve(value)), duration) }); } sleepAndReturn(1000, 'done') .then((result) => { console.log(result); / / result now equals 'done' })
  13. PROMISE CHAINING sleepAndReturn(1000, 'done') .then((result1) => { return `${result1} ah

    hihi` }) .then((result2) => { console.log(result2); / / result2 now equals 'done ah hihi' });
  14. PROMISE CHAINING sleepAndReturn(1000, 'done') .then((result1) => { return sleepAndReturn(1000, `${result1}

    ah hihi`) }) .then((result2) => { console.log(result2); / / result2 now equals 'done ah hihi' });
  15. PROMISE CHAINING sleepAndReturn(1000, 'done') .then((result) => { throw new Error('Ops...');

    }) .then((result1) => { / / do something }) .then((result2) => { / / do one more thing }) .catch((error) => { handleError(error); });
  16. FROM THIS … getData(function(a) { getMoreData(function(b) { getMoreData(function(c) { getMoreData(function(d)

    { getMoreData(function(e) { / / do something }); }); }); }); });
  17. TO THIS! getData() .then(getMoreData) .then(getMoreData) .then(getMoreData) .then(getMoreData) .then((result) => {

    / / do something }) .catch((error) => { handleError(error); });
  18. PROMISE IS GOOD BECAUSE … > It is easier to

    read as in cleaner method signatures. > It allows us to attach more than one callback to a single promise. > It allows for chaining of promises.
  19. COMMON MISTAKES > One traditional example of using promises is

    promise.then(resolve, reject); > Exception in success handler goes unnoticed.
  20. COMMON MISTAKES > Test case at https:/ /github.com/codeaholicguy/promise-misses-error

  21. BUT! > It is still quite cumbersome to handle even

    simple logic. Don't you believe? Just thinking about making a for-loop with promises…
  22. BLUEBIRD HELPERS Promise.any Promise.map Promise.reduce Promise.filter Promise.each

  23. BUT IT IS STILL 3RD LIBRARY … > See you

    next time with Generator & async/await (ES7) THANKS FOR LISTENING! > GITHUB @codeaholicguy > FACEBOOK @codeaholicguy