Last active
November 11, 2019 23:18
-
-
Save Jxck/8380852 to your computer and use it in GitHub Desktop.
ジェネレータの解説と非同期への適用 完成品 http://jxck.hatenablog.com/entry/2014-01-12/generator-screencaset
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
b.txt |
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
c.txt |
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
goal! |
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 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); | |
} | |
} | |
} |
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
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