LoginSignup
3
2

More than 5 years have passed since last update.

yield + setTimeoutの謎を追う

Last updated at Posted at 2016-03-28

子曰く

これでsleep良い感じに書けるぜ。

var co = require('co');

function sleep(ms) {
  return function (cb) {
    setTimeout(cb, ms);
  };
}

// var sleep = require('co-sleep');

co(function *() {
  for (var i = 0; i < 5; ++i) {
    console.log('message1 - ' + i);
    yield sleep(1000);
    console.log('message2 - ' + i);
    yield sleep(1000);
    console.log('message3 - ' + i);
  }
  return 'final value';
});

私、理解できず Node.js v4.2.6で試す

> function sleep(msec) {return function(cb){ console.log("xxxxx",cb);}}

> co(function*(){yield sleep(1000);}).then(function(){console.log("end")})

こうしてみたら、

xxxxx function (err, res) {
      if (err) return reject(err);
      if (arguments.length > 2) res = slice.call(arguments, 1);
      resolve(res);
    }

こんなん来ました。

なるほど

https://github.com/tj/co/blob/master/index.js#L134-L143
要するにcoがyieldを処理するときにPromiseなFunctionを暗黙に渡してくるようです。

Thunk? Thunk? モニカ?

  return function (cb) {
    setTimeout(cb, ms);
  };

これにはthunkというシャレオツな名前が付いているのを知りませんでした。

を見るとcoが取り扱えるyieldableとしてthunkも入っており、上記でリンクしたthunkToPromiseがPromiseに変換してくれるようです。

でも

悩むから、冗長ですがこう書こうと思いました。

function sleep(ms) {
  return new Promise(function(resolve) {
    setTimeout(function() {
      resolve();
    }, ms);
  });
}
3
2
4

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
3
2