Skip to content

Instantly share code, notes, and snippets.

@alekseykulikov alekseykulikov/index.js
Last active Dec 18, 2015

Embed
What would you like to do?
Use es6 generators to simplify async calls.
/**
* 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');
}
});
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
You can’t perform that action at this time.