Skip to content

Instantly share code, notes, and snippets.

@alekseykulikov
Last active December 18, 2015 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alekseykulikov/5840765 to your computer and use it in GitHub Desktop.
Save alekseykulikov/5840765 to your computer and use it in GitHub Desktop.
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