node: コルーチンで同期的に処理する

nodebrewでv0.11.14をインストールしたら、コルーチンが使えるようになったのでとりあえずメモ。

#!/usr/bin/env node --harmony
var AWS = require('aws-sdk');

var ec2 = new AWS.EC2();

var main = (function*() {
  yield ec2.describeInstances({}, function(err, data) {
    console.log("num(1): ", data.Reservations.length);
    main.next();
  })

  yield ec2.describeInstances({}, function(err, data) {
    console.log("num(2): ", data.Reservations.length);
    main.next();
  })

  console.log('end of script');
})();

main.next();
num(1):  7
num(2):  7
end of script

main.next()が終わった時点で、イベントループのタスク解消待ちに入って同期的に処理される。 スクリプト末尾のイベントループ解消待ちが、非同期の世界ではありなのかなぁ…と思ってもやもやする。

ところで

(function*() {
  ...
})().next();

と書いたらTypeError: undefined is not a functionになった。何でだろ?