LoginSignup
2
2

More than 5 years have passed since last update.

コルーチンを補助するco-gateモジュールを公開しました.

Posted at

co(koa.js)は中で何をしているのか.の続き.

co用のゲートモジュールco-gateを公開しました.
visionmedia/coを使うと、非同期APIを同期的に使うことが出来るのは、今までのエントリに書いた通りです.
ただ、ThunkやPromiseにAPIを書き換えなければいけません.

そこでco-gateでは、非同期APIのコールバックをゲートに入れて(gate.in())、同期的にゲートから出す(gate.out())ことで、従来型のAPIをそのままで使うことが出来るようにしています.

// require co
var co = require('co')
  , Gate = require('co-gate')
  , fs = require('fs');


co(function *(){
  // create gate
  var gate = new Gate()
    , val = undefined;

  // just call normal apis with gate.in() as callback
  fs.readFile("test/test1.txt", "utf-8", gate.in());
  fs.readFile("test/test2.txt", "utf-8", gate.in());

  try{
    // yielded
    val = yield gate.out();
  }catch(e){
    console.log(e);
  }

  assert.equal(val[0], 'test1');
  assert.equal(val[1], 'test2');

})();

このモジュールはGo風のチャンネルモジュールであるchanに発想を得ています.興味のある人はchanと見比べてみると面白いと思います.

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2