Last active
April 19, 2018 10:09
-
-
Save elston/6704c5afe97d3c8a5970da1562b2732f to your computer and use it in GitHub Desktop.
extremely easy generators router for sync and async code samples :)
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
| /* | |
| ** | |
| */ | |
| const genRouter = function(gen){ | |
| this.gen = gen | |
| this.value = null | |
| } | |
| genRouter.prototype.run = function(){ | |
| this.next() | |
| } | |
| genRouter.prototype.next = function(){ | |
| // .. | |
| const { value:fn, done } = this.gen.next(this.value) | |
| // ... | |
| if(!done) | |
| fn.call(this, this.callback) | |
| } | |
| genRouter.prototype.callback = function(err, data){ | |
| // ... | |
| if (err) | |
| return this.gen.throw(err) | |
| // .. | |
| this.value = data | |
| this.next() | |
| } | |
| /* | |
| ** | |
| */ | |
| const asyncEcho = function(data) { | |
| return function(cb){ | |
| let err = false | |
| setTimeout(() => cb.call(this, err, data), 2000) | |
| } | |
| } | |
| const Echo = function(data){ | |
| return data | |
| } | |
| const Echoes = function*() { | |
| // .. | |
| console.log('..waiting from echo1') | |
| const echo1 = yield asyncEcho('this') | |
| console.log('..done') | |
| // .. | |
| console.log('..waiting from echo2') | |
| const echo2 = yield asyncEcho(echo1 + ' ' + 'is') | |
| console.log('..done') | |
| // ... | |
| console.log('..waiting from echo3') | |
| const echo3 = Echo(echo2 + ' ' + 'a test') | |
| console.log('..done') | |
| // .. | |
| console.log('..waiting from echo4') | |
| const echo4 = yield asyncEcho(echo3 + ' ' + 'of generators') | |
| console.log('..done') | |
| console.log(echo4) | |
| }; | |
| // .. | |
| const echoes = Echoes() | |
| const router = new genRouter(echoes) | |
| router.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment