Bluebird Promise에서의 Coroutine사용방법
참조
https://github.com/petkaantonov/bluebird/blob/master/API.md#generators
필수
Node.js >= 0.11.2(현 시점에서 0.12.0이 stable)
수순
실행 커맨드는 이하와 같다. app을 기동할때 다음과 같은 옵션이 필요하다
node --harmony-generators app.js
혹은
node --harmony app.js
mocha 테스트에 있어서도 --harmony옵션을 붙여서 실행할 필요가 있다.
참조 공식 문서로부터 수정한 coroutine 사용예제 (for sails.js)
/**
* CoroutineController
*
* @description :: Server-side logic for managing coroutines
* @help :: See http://links.sailsjs.org/docs/controllers
*/
var Promise = require("bluebird");
function PingPong() {
}
PingPong.prototype.ping = Promise.coroutine(function* (val,lim,cb) {
console.log("Ping?", val);
yield Promise.delay(1); // ms
if(val < lim) {
this.pong(val+1,lim,cb);
}
else
{
cb();
}
});
PingPong.prototype.pong = Promise.coroutine(function* (val,lim,cb) {
console.log("Pong!", val);
yield Promise.delay(1); // ms
if(val < lim) {
this.ping(val + 1,lim,cb)
}
else
{
cb();
}
});
module.exports = {
test:function(req,res,next) {
var pingpong = new PingPong();
pingpong.ping(0,5000,function() {
console.log("done");
res.json({"message":"done"});
});
}
};
결과
Ping? 0
Pong! 1
...
Ping? 4996
Pong! 4997
Ping? 4998
Pong! 4999
Ping? 5000
Pong! 5001
done
댓글 없음:
댓글 쓰기