yoshi2perth / playground

0 stars 0 forks source link

【調査】【Node.js】coがわからない #4

Open yoshi2perth opened 9 years ago

yoshi2perth commented 9 years ago
var co = require('co');
var fs = require('fs');

co(function *() {
  var files = yield co.wrap(fs.readdir)('.');
  var data = yield co.wrap(fs.readFile)(files[0], 'utf-8');
  console.log(data);
});

yieldって処理が途中で止まる以外returnと同じ挙動だと思うのだけど、var hoge = return 1;とかって普通書かないし、そもそものyieldの認識が間違ってるのかしら??

yoshi2perth commented 9 years ago

send()っていうのがあるのね。。。と思ったらundefinedとな!

$ node --harmony test_send.js 
/Users/kyoshiok/mygit/playground/yield-test/test_send.js:10
gen.send("xx");
    ^
TypeError: undefined is not a function
    at Object.<anonymous> (/Users/kyoshiok/mygit/playground/yield-test/test_send.js:10:5)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:124:16)
    at node.js:842:3
yoshi2perth commented 9 years ago

v8ではnext()に引数書くとsend()と同じ挙動になるらしい。 (こういう仕様ってどこに書いてあるんだろ。。。)

gen.next(hoge);
yoshi2perth commented 9 years ago

自分でcoっぽいのを書いてみた。なんとなく理解。 https://github.com/yoshi2perth/playground/blob/master/yield-test/myco.js https://github.com/yoshi2perth/playground/blob/master/yield-test/myco_test.js

yoshi2perth commented 9 years ago

ちょっとまて。コールバックの https://github.com/yoshi2perth/playground/blob/55fde67d43d35bbf6d6be06ee84d9c075a7d9a2f/yield-test/myco.js#L11 ここだけど、第2引数にresultが入るのはcoは知っているの? あとerrがどんな状態だったらthrowすればいいか知ってるの? コールバックのフォーマットなんて実行する関数によって違うと思うんだけど。。。 promiseとかが関係してくるのかな??