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

Async Patterns & Paradigms in Javascript

Async Patterns & Paradigms in Javascript

We examine some common and some quite new async patterns in Javascript. Inspired by a great workshop in advanced JS by Kyle Simpson

Project companion: https://github.com/th3hunt/js-async-patterns

39faa5e8e938d2fbd92acc2e8ebdf65b?s=128

Stratos Pavlakis

January 29, 2016
Tweet

Transcript

  1. Async Patterns in Javascript

  2. Stratos Pavlakis Workable UI Tech Lead pavlakis@workable.com Async Patterns in

    JS Sokratis Vidros Senior Software Engineer @ Workable sokratis@workable.com
  3. Concurrency & Parallelism

  4. Concurrency VS Parallelism Concurrency Two or more tasks are happening

    at the same interval Parallelism Two or tasks are happening at the exact same instant (e.g. multicore processors)
  5. Companion

  6. Companion Scenarios • South Park • Aragorn Lineage https://github.com/th3hunt/js-async-patterns

  7. Callbacks

  8. Callbacks • An executable piece of code • Passed as

    an argument • Expected to be “called back” at some point in time
  9. Deferred Execution

  10. Event Driven UI

  11. Callback Problems

  12. Pyramid of Doom ?

  13. Better with CPS?

  14. Not really...

  15. Not reasonable

  16. • Grant control to another party • Loss of trust

    ◦ Truly async? ◦ # of executions ◦ Execution context ◦ Error handling Inversion of Control
  17. Promises

  18. Promises • A future value representation that emits completion events

    • Facilitate sequential and parallel flow control • Chainable through a “thenable” interface • Allows deferring callback setup
  19. ES6 Native Promises Superset of Promise A+ specification

  20. Promises in real life

  21. Flow control Sequential Parallel

  22. So what?

  23. Promise Trust • Always async, even if already settled •

    Encapsulate state • Either success or fail • Always resolve or reject only once • Become immutable once resolved • Facilitate error handling
  24. Always async? Tasks Triggers such as DOM events and setTimeout

    enqueue tasks Microtasks Scheduled for things that should happen straight after the currently executing task. Promise callbacks are usually called as microtasks.
  25. Promise Toolbelt • ES6 Polyfill - github.com/jakearchibald/es6-promise/ • Q -

    github.com/kriskowal/q • Bluebird - github.com/petkaantonov/bluebird • And many more - promisesaplus.com/implementations
  26. Observables

  27. Observables • Lazy event streams which can emit zero or

    more events, and may or may not finish • Values can be Promises or other Observables • EventEmitter API + Iterable API = Pub/Sub model on steroids
  28. How to build a searchbox?

  29. Refined searchbox

  30. Observables • Frameworks ◦ RxJS - github.com/Reactive-Extensions/RxJS ◦ BaconJS -

    baconjs.github.io ◦ Cycle.js - cycle.js.org ◦ Kefir.js - rpominov.github.io/kefir • 9th GreeceJS speakerdeck.com/pavlakis/introduction-to-frp
  31. Generators

  32. Generators • A special coroutine in the form of an

    iterable function • Preserves its context across re-entrances
  33. Play & Pause Interface yield next

  34. Live demo

  35. Why Generators? • Handle asynchronicity in a synchronous fashion by

    yielding promises • Alleviate the need for callbacks • Elegant error handling - throw & try/catch wrapping
  36. Synchronous Fashion

  37. Generators in Practice • Allow async tasks to suspend the

    execution of their caller ◦ File handling ◦ Sockets ◦ Sleeps ◦ Network requests ◦ Animations • Koa framework - koajs.com
  38. Thunks

  39. Thunks • A function that wraps some behavior for later

    execution • Accepts only a callback as an argument • Enforces the CPS paradigm • May return another thunk - aka chainable
  40. Thunkify github.com/tj/node-thunkify github.com/thunks/thunks

  41. Thunkify a file read

  42. Origins - call by name • Assists the call to

    another subroutine • Wraps the unevaluated argument in a function • Enables lazy evaluation
  43. Why thunks? • Thunks can be used as yieldable structures

    for generator based flow controllers as an alternative to Promises • Co - github.com/tj/co • Redux-thunk - github.com/gaearon/redux-thunk
  44. Using with Generators

  45. Communicating Sequential Processes

  46. CSP • Coordination via message passing based on channels •

    Channels are 2-way streams (default buffer = 1) • A channel cannot accept a message unless someone on the other side is reading • JS-CSP: Operations on channels are yieldable from inside generators
  47. Example

  48. None