Created
April 15, 2015 05:06
-
-
Save nickfargo/c5a5f87a10d82de1a7d1 to your computer and use it in GitHub Desktop.
Convert a CSP generator function (“goroutine”) into a Node-style async function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # ES6 | |
| async = (generator) -> | |
| g = (args..., callback) -> | |
| try callback null, yield receive go generator, args | |
| catch error then callback error | |
| return | |
| (_) -> proc g, arguments; return | |
| # ES5 | |
| async = do -> | |
| class AsyncIterator | |
| constructor: (@generator, @args, @callback) -> | |
| @step = 0 | |
| @result = value: undefined, done: no | |
| next: (input) -> | |
| switch ++@step | |
| when 1 | |
| output = receive go @generator, @args | |
| when 2 | |
| try output = @callback null, input | |
| catch error then @callback error | |
| @result.done = yes | |
| @result.value = output | |
| @result | |
| async = (generator) -> (_) -> | |
| g = (args..., callback) -> new AsyncIterator generator, args, callback | |
| proc g, arguments | |
| return |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // ES6 | |
| function async (generator) { | |
| function* g (...args) { | |
| let callback = args.pop(); | |
| try { | |
| callback(null, yield receive(go(generator, args))); | |
| } catch (error) { | |
| callback(error); | |
| } | |
| } | |
| return function (_) { | |
| proc(g, arguments); | |
| }; | |
| } | |
| // ES5 | |
| var async = (function () { | |
| function AsyncIterator (generator, args, callback) { | |
| this.generator = generator; | |
| this.args = args; | |
| this.callback = callback; | |
| this.step = 0; | |
| this.result = {value: void 0, done: false}; | |
| } | |
| AsyncIterator.prototype.next = function (input) { | |
| var output; | |
| switch (++this.step) { | |
| case 1: | |
| output = receive(go(this.generator, this.args)); | |
| break; | |
| case 2: | |
| try { | |
| output = this.callback(null, input); | |
| } catch (error) { | |
| this.callback(error); | |
| } | |
| this.result.done = true; | |
| } | |
| this.result.value = output; | |
| return this.result; | |
| }; | |
| return function (generator) { | |
| return function (_) { | |
| function g () { | |
| var args = Array.prototype.slice.call(arguments); | |
| var callback = args.pop(); | |
| return new AsyncIterator(generator, args, callback); | |
| } | |
| proc(g, arguments); | |
| }; | |
| }; | |
| }()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment