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

Yield! Javascript Generators and Monocle.js

Yield! Javascript Generators and Monocle.js

In this talk I explain generators, a new Javascript feature coming in ES6. I then discuss the Monocle.js library, which uses generators to make writing asynchronous code much cleaner.

Jonathan Lipps

August 29, 2013
Tweet

More Decks by Jonathan Lipps

Other Decks in Programming

Transcript

  1. In ES6, a bold new world awaits, ripe for the

    plunder of its sweet fruits!* * This is meant to be humorous. Remember kids: imperialism is bad.
  2. My favorite is the generator, a new type of function

    whose execution can be externally controlled \
  3. Things to remember Calling a Generator returns an Iterator Iterators

    have a next() method Calling next() returns whatever is after the next yield statement in the generator
  4. Things to remember next() actually returns an object, with keys

    value and done Calling next() with a parameter sends that value in as the result of the generator’s last yield Calling next() always returns whatever is after the next yield statement in the generator, even if you are also sending in a value
  5. Hang on a minute! If we can arbitrarily pause function

    execution, and send values back in...
  6. ...we can tell the generator to wait until we’ve received

    the result of an asynchronous function’s callback...
  7. monocle.js is a library that lets you use a blocking-like

    syntax with async functions in generators
  8. Inside an o-routine, you can: yield to another o-routine: pause

    execution until the other o-routine has completed return the result of this o-routine: pass a response to an o-routine waiting on us
  9. But... yield? yield in generators usually acts like yield “as

    in crops”: it provides a result to next() yield in o-routines acts like yield “as in traffic”: it waits for something else to nish.
  10. You can then yield to this special callback, and monocle

    will wait for it as if it were an o-routine
  11. Wd is a Node.js client library that implements this protocol.

    Appium uses Wd to write all its tests.
  12. Yiewd is a monoclized version of Wd that converts all

    automation functions into o-routines
  13. In sum, monocle.js uses JS generators to open up a

    whole new world of code quality