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

You don't know Promises - IT Konekt April 2019

You don't know Promises - IT Konekt April 2019

4ff4d0c579ce1bdbe505d8317e158a20?s=128

Ivan Jovanovic

April 20, 2019
Tweet

Transcript

  1. You don't know Promises

  2. I am Ivan Jovanovic Senior Software Engineer, Tech Speaker You

    can find me at @ivanjov96 or https://ivanjov.com Hello! IJ Consulting
  3. Why I don't know Promises?

  4. None
  5. None
  6. I am here today To show you how Promises really

    work!
  7. JavaScript is strange because ‒ It was built for 10

    days ‒ It has one thread ‒ It is synchronous and asynchronous ‒ It is everywhere ‒ It is different
  8. Only one thread And the event loop

  9. None
  10. How do we handle async code? Promises Callbacks Async/await

  11. Callbacks Where everything began... 1

  12. “ A callback is a function that is passed as

    an argument and will be executed after another function has finished executing.
  13. None
  14. None
  15. Promises Changed everything 2

  16. “ The Promise object represents the eventual completion (or failure)

    of an asynchronous operation, and its resulting value.
  17. None
  18. None
  19. How Promises really work? The answer is a Microtask queue!

  20. None
  21. Microtask queue ‒ Independent queue ‒ Used by: process.nextTick, Promises,

    Object.observe, MutationObserver ‒ Faster than the main queue and may be drained several times in a single event loop tick
  22. None
  23. Next TICK ONE Next TICK TWO TIMEOUT AFTER-ONE TIMEOUT AFTER-TWO

  24. Promise methods ‒ Promise.all(iterable) ‒ Promise.race(iterable) ‒ Promise.resolve(value) ‒ Promise.reject(reason)

  25. Promise.all(iterable)

  26. Rejected situation

  27. Promise.race(iterable)

  28. Promisify non-Promise code

  29. Native Promises from libraries

  30. Async/await Comes to the rescue 3

  31. “ Async/Await is a special syntax for working with Promises.

  32. None
  33. Most common problems with Promises that we see every day!

    9
  34. Nested promises 1

  35. None
  36. None
  37. Broken Promise chain 2

  38. None
  39. None
  40. Mixing sync and async code 3

  41. None
  42. None
  43. None
  44. Missing catch 4

  45. None
  46. None
  47. None
  48. Forget to return a Promise 5

  49. None
  50. None
  51. Promisified synchronous code 6

  52. None
  53. Mixing Promise and Async/Await 7

  54. None
  55. None
  56. Async function that returns Promise 8

  57. None
  58. None
  59. None
  60. Define a callback as an async function 9

  61. None
  62. Clinic.js https://clinicjs.org/

  63. Conclusion ‒ JS is crazy and great at the same

    time! ‒ Async behavior is a pro, not a con. ‒ Be careful when using Promises, it's great and dangerous at the same time!
  64. Any questions ? You can find me at ‒ @ivanjov96

    ‒ hi@ivanjov.com Thanks!