Skip to content

Instantly share code, notes, and snippets.

@Jxck
Last active Nov 11, 2019
Embed
What would you like to do?
ジェネレータの解説と非同期への適用 完成品 http://jxck.hatenablog.com/entry/2014-01-12/generator-screencaset
var fs = require('fs');
co(function* generator() {
var read = thunkify(fs.readFile);
try {
var path = 'a.txt';
var b = yield read(path, 'utf8');
b = b.replace('\n', '');
var c = yield read(b, 'utf8');
c = c.replace('\n', '');
var result = yield read(c, 'utf8');
result = result.replace('\n', '');
console.log(result);
} catch (err) {
console.error(err);
}
})();
///////////////////////////////////////////////////////
function co(generator) {
var g = generator();
function done(err, data) {
if (err) {
return g.throw(err);
}
var n = g.next(data);
if (n.done) {
return;
}
n.value(done);
}
return function() {
g.next().value(done);
}
}
function thunkify(fn) {
return function() {
var args = Array.prototype.slice.call(arguments);
return function(callback) {
args.push(callback);
fn.apply(this, args);
}
}
}
function* generator() {
var a = yield(function() { console.log('x'); return 1 })();
console.log(a);
var b = yield(function() { console.log('y'); return 2 })();
console.log(b);
var c = yield(function() { console.log('z'); return 3 })();
console.log(c);
return 4;
}
var g = generator();
console.log(g.next());
console.log(g.next(10));
console.log(g.next(20));
console.log(g.next(30));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment