node.jsで使える非同期コントロールフローライブラリ nue その10 - node-seqのサンプルと比較
GREEではnode-seqを使っているんですね。
気になったのでnode-seq(https://github.com/substack/node-seq/tree/master/examples)のサンプルをnueで実装したらどうなるか試してみました。
stat_all.js
var flow = require('nue').flow; var fs = require('fs'); flow('stat_all')( function readdir() { fs.readdir(__dirname, this.async()); }, function stat(files) { process.nextTick(this.async(files)); files.forEach(function (file) { fs.stat(__dirname + '/' + file, this.async()) }.bind(this)); }, function end(files) { if (this.err) throw this.err; var statsArray = this.args.slice(1); var sizes = files.reduce(function (obj, key, i) { obj[key] = statsArray[i].size; return obj; }, {}); console.log(sizes); this.next(); } )();
parseq.js
var flow = require('nue').flow; var fs = require('fs'); var exec = require('child_process').exec; flow('parseq')( function whoami() { exec('whoami', this.async()); }, function parallel(who) { exec('groups ' + who, this.async()); fs.readFile(__filename, 'ascii', this.async()); }, function end(groups, stderr, src) { if (this.err) throw this.err; console.log('Groups: ' + groups.trim()); console.log('This file has ' + src.length + ' bytes'); this.next(); } )();
join.js
var flow = require('nue').flow; flow('join')( function parallel() { setTimeout(this.async('a'), 300); setTimeout(this.async('b'), 200); setTimeout(this.async('c'), 100); }, function end(a, b, c) { if (this.err) throw this.err; console.dir([ a, b, c ]); this.next(); } )();
感触としては、stat_all.jsについてははnode-seqのほうが簡潔に書けた、parseq.jsとjoin.jsについてはnueのほうが簡潔に書けた、という感じです。
nueは配列の扱いにもう一工夫あってもいいかもしれないなあ。配列のforEachがあれば事足りるとか思ったものの。
イメージとしてはこういう感じで書けるといいかも。
上記stat_all.js改良イメージ
var flow = require('nue').flow; var each = require('nue').each; var fs = require('fs'); flow('stat_all')( function readdir() { fs.readdir(__dirname, this.async()); }, each(function stat(file) { fs.stat(__dirname + '/' + file, this.async(file)) }), function end() { if (this.err) throw this.err; var sizes = this.args.reduce(function (obj, result) { obj[result[0]] = result[1].size; return obj; }, {}); console.log(sizes); this.next(); } )();