Last active
December 18, 2015 20:29
-
-
Save alekseykulikov/5840765 to your computer and use it in GitHub Desktop.
Use es6 generators to simplify async calls.
This file contains 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
/** | |
* Required node >= v0.11.2 | |
* usage: node --harmony index.js | |
*/ | |
var fs = require('fs'); | |
var run = require('./run'); | |
function readFile(filename) { | |
return fs.readFile.bind(fs, filename, 'utf-8'); | |
} | |
run(function* example() { | |
var a = yield readFile(__filename); | |
var b = yield readFile('package.json'); | |
var c = yield readFile('.gitignore'); | |
console.log(a, b, c); | |
try { | |
yield readFile('foo-bar.js'); | |
} catch (e) { | |
console.log('foo-bar.js does not exists'); | |
} | |
}); |
This file contains 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
var slice = [].slice; | |
function run(fn) { | |
var gen = fn(); | |
function next(err, val) { | |
if (err) { | |
gen.throw(err); | |
} else { | |
var res = gen.send(val); | |
if (!res.done) res.value(next); | |
} | |
} | |
next(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment