Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

The evolution of asynchronous javascript

1,490 views

Published on

One of JavaScript’s strengths is how it handles asynchronous code. Async is one of the most important and often misunderstood part of Javascript or any other language. Async is hard because we, as human beings, can’t do two conscious actions at once and think about both of them at the same moment. In this talk we will see how asynchronous JavaScript evolved over the years. It all started with callbacks… and it landed on generators!

Published in: Technology
  • Login to see the comments

The evolution of asynchronous javascript

  1. 1. THE EVOLUTION OF ASYNCHRONOUS JAVASCRIPT @cirpo
  2. 2. now & later ASYNCRONY
  3. 3. the core of asynchronous programming is the relationship between the now and later parts of your program ASYNCRONY
  4. 4. how to express, manage and manipulate program behaviours over a period of time?
  5. 5. CONCURRENCY
  6. 6. CONCURRENCY a way to structure a program by breaking it into pieces that can be executed independently
  7. 7. IS JS CONCURRENT?
  8. 8. A JS runtime contains a message queue, which is a list of messages to be processed. To each message is associated a function. When the stack is empty, a message is taken out of the queue and processed. QUEUE
  9. 9. function f(b){ var a = 12; return a+b+35; } function g(x){ var m = 4; return f(m*x); } g(21); STACK
  10. 10. function f(b){ var a = 12; return a+b+35; } function g(x){ var m = 4; return f(m*x); } g(21); 1 foo gets called STACK
  11. 11. function f(b){ var a = 12; return a+b+35; } function g(x){ var m = 4; return f(m*x); } g(21); 2 first frame is created containing foo and local variable 1 foo gets called STACK
  12. 12. function f(b){ var a = 12; return a+b+35; } function g(x){ var m = 4; return f(m*x); } g(21); 2 first frame is created containing foo and local variable 1 foo gets called 3 when foo calls bar, a second frame is push on top of foo, containing bar arguments and local variables STACK
  13. 13. function f(b){ var a = 12; return a+b+35; } function g(x){ var m = 4; return f(m*x); } g(21); 4 when bar returns, the top frame element is popped out of the stack (leaving only foo call frame) STACK
  14. 14. function f(b){ var a = 12; return a+b+35; } function g(x){ var m = 4; return f(m*x); } g(21); 5 When foo returns, the stack is empty 4 when bar returns, the top frame element is popped out of the stack (leaving only foo call frame) STACK
  15. 15. EVENT LOOP
  16. 16. JS IS NON BLOCKING
  17. 17. events eventloop net filesystem … event queue thread pool
  18. 18. JS unlike a lot of other languages, never blocks Handling I/O is typically performed via events and callbacks When the application is waiting for an IndexedDB query to return or an XHR request to return, it can still process other things like user input JS IS NON BLOCKING
  19. 19. Node.js is great for Input/Output processing but not optimised for CPU-bound work like performing a large amount of calculations. JS IS NON BLOCKING
  20. 20. Up until recently (ES6), JS itself has actually never had any direct notion of asynchrony built into it
  21. 21. JS runs inside a hosting environment (the browser/nodejs) The event loop is handled by it
  22. 22. IS JS CONCURRENT?
  23. 23. goroutinesprocesses
  24. 24. IS JS CONCURRENT?
  25. 25. JS IS SINGLE THREAD
  26. 26. SORT OF …
  27. 27. BUT THE HOSTING ENVIRONMENT CAN USE MULTI THREAD
 FOR I/O OPERATIONS
  28. 28. most devs new to JS have issues with the fact that later doesn’t happen strictly and immediately after now ASYNCRONY
  29. 29. tasks that cannot complete now are, by definition, going to complete asynchronously and thus no blocking behaviour as it might intuitively expect or want. ASYNCRONY
  30. 30. ASYNCRONY
  31. 31. ASYNC IS GREAT
  32. 32. BUT CAN BE HARD
  33. 33. SEQUENTIAL BRAIN
  34. 34. SEQUENTIAL BRAIN put aside involuntary, subconscious, automatic brain functions we are not multitasker
  35. 35. SEQUENTIAL BRAIN As soon as we introduce a single continuation in the form of a callback function, we have allowed a divergence to form between how our brains work and the way the code will operate
  36. 36. can we do that?
  37. 37. yes… but we are blocking
  38. 38. WHEN YOU BLOCK, YOU “PULL” A VALUE
  39. 39. CALLBACK
  40. 40. PIRAMID OF DOOM!
  41. 41. CALLBACK HELL!
  42. 42. BULLSHIT
  43. 43. HOW TO AVOID POD
  44. 44. HOW TO AVOID POD
  45. 45. ASYNC CALLBACK
  46. 46. ASYNC CALLBACK =
  47. 47. ASYNC CALLBACK PUSH =
  48. 48. LOSS OF CONTROL FLOW
  49. 49. LOSS OF ERROR HANDLING
  50. 50. INVERSION OF CONTROL
  51. 51. “Don't call us, we'll call you”
  52. 52. INVERSION OF CONTROL
  53. 53. INVERSION OF CONTROL what if it’s a third party call not under our control?
  54. 54. INVERSION OF CONTROL
  55. 55. INVERSION OF CONTROL what if it’s never called?
  56. 56. INVERSION OF CONTROL what if it’s never called? what if it’s called too early?
  57. 57. INVERSION OF CONTROL what if it’s never called? what if it’s called too early? what if it’s called too late?
  58. 58. meh.
  59. 59. HOW CAN YOU TELL IF IT’S AN ASYNC CALL?
  60. 60. meh.
  61. 61. Callbacks are the fundamental unit of asynchrony in JS. But they’re not enough for the evolving landscape of async programming as JS matures. I <3 callbacks
  62. 62. PROMISES
  63. 63. PROMISES It allows you to associate handlers to an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of the final value, the asynchronous method returns a promise. A promise represents a proxy for a value not necessarily known when the promise is created.
  64. 64. PROMISES http://ecma-international.org/ecma-262/6.0/#sec-jobs-and-job-queues
  65. 65. PROMISES Promises are now the official way to provide async return values in both JavaScript and the DOM. All future async DOM APIs will use them, and many already do, so be prepared!
  66. 66. PROMISES pending: initial state, not fulfilled or rejected fulfilled: the operation completed successfully rejected: meaning that the operation failed.
  67. 67. PROMISES always async returns a promise handled once thenable
  68. 68. PROMISES A promise must provide a then method to access its current or eventual value or rejection reason .then()
  69. 69. PROMISES .then(onFulfilled, onRejected)
  70. 70. PROMISES can return a promise .then()
  71. 71. PROMISES .then() .then() .then()
  72. 72. PROMISES .catch()
  73. 73. Talk is cheap, show me the code
  74. 74. PROMISES
  75. 75. PROMISES
  76. 76. PROMISES inversion of control async or sync? error handling control flow
  77. 77. WIN!
  78. 78. BUT …
  79. 79. PROMISE HELL!
  80. 80. AVOID PROMISE HELL!
  81. 81. AVOID PROMISE HELL!
  82. 82. DON’T USE PROMISES FOR CONTROL FLOW
  83. 83. YOUR CODEBASE THEN BECOMES PROMISE DEPENDANT
  84. 84. USING PROMISES EVERYWHERE IMPACTS ON THE DESIGN
  85. 85. TO PROMISE OR TO CALLBACK?
  86. 86. IF YOU HAVE A LIBRARY, SUPPORT BOTH
  87. 87. SINGLE VALUE
  88. 88. SINGLE RESOLUTION BAD FOR STREAMS
  89. 89. SINGLE RESOLUTION
  90. 90. PERFORMANCES
  91. 91. PERFORMANCES Promises are slower compared to callbacks You don’t get rid of callbacks, they just orchestrate callbacks in a trustable way
  92. 92. PERFORMANCES Promises are slower compared to callbacks You don’t get rid of callbacks, they just orchestrate callbacks in a trustable way99.9% of the time you won’t feel it
  93. 93. PROMISES
  94. 94. WHAT IF WAITING WERE JUST AS EASY AS BLOCKING?
  95. 95. GENERATORS
  96. 96. GENERATORS A new type of function that does’t not behave with the run-to-completion behaviour
  97. 97. GENERATORS
  98. 98. GENERATORS 1 constructing the iterator, not executing
  99. 99. GENERATORS 1 constructing the iterator, not executing 2 starts the iterator
  100. 100. GENERATORS 1 constructing the iterator, not executing 2 starts the iterator 3 pause the iterator
  101. 101. GENERATORS 1 constructing the iterator, not executing 2 starts the iterator 4 resume the iterator 3 pause the iterator
  102. 102. GENERATORS 1 constructing the iterator, not executing 2 starts the iterator 4 resume the iterator 3 pause the iterator
  103. 103. GENERATORS with the yield where are pausing
  104. 104. GENERATORS A.K.A BLOCKING! with the yield where are pausing
  105. 105. GENERATORS
  106. 106. GENERATORS iterator is just one side…
  107. 107. GENERATORS the other side is an observable
  108. 108. GENERATORS
  109. 109. GENERATORS
  110. 110. GENERATORS
  111. 111. GENERATORS
  112. 112. GENERATORS
  113. 113. we can block! we can pull values we can push values GENERATORS
  114. 114. GENERATORS + PROMISES
  115. 115. the iterator should listen for the promise to resolve then either resume the generator with the fulfilment message (or throw an error into the generator with the rejection reason) GENERATORS + PROMISES
  116. 116. GENERATORS + PROMISES
  117. 117. GENERATORS + PROMISES
  118. 118. GENERATORS + PROMISES
  119. 119. GENERATORS + PROMISES npm install co
  120. 120. BUT…
  121. 121. ES7 ES2016 to the rescue!
  122. 122. async/await
  123. 123. async/await
  124. 124. npm install -g babel-cli babel a.es6 -o a.js node a.js //add it either to .babelrc or package.json { "plugins": ["transform-async-to-generator"] } npm install babel-plugin-transform-async-to-generator
  125. 125. STREAMS
  126. 126. callbacks async/await
  127. 127. CHOOSE YOUR CONCURRENCY MODEL
  128. 128. A big thanks to Kyle Simpson (@getify) github.com/getify/You-Dont-Know-JS
  129. 129. @federicogalassi @unlucio … and my mentors slideshare.net/fgalassi slideshare.net/unlucio
  130. 130. @loige @mariocasciaro youtube.com/watch?v=lil4YCCXRYc
  131. 131. @cirpo Dev lead at github.com/cirpo http://sainsburys.jobs
  132. 132. THANK YOU!

×