lazyman 실현

1738 단어

function _lazyman(name) {
this.tasks = [];
var self = this;
var fn = function() {
console.log("hi this is " + name);
self.next();
}
this.tasks.push(fn);
setTimeout(function() {
self.next();
}, 0);
}
// next
_lazyman.prototype.next = function() {
// body...
var fn = this.tasks.shift();
fn && fn();
};
_lazyman.prototype.eat = function(name) {
// body...
var self = this;
var fn = function() {
console.log("eat " + name + " ~");
self.next();
}
this.tasks.push(fn);
//
return this;
};
_lazyman.prototype.sleep = function(time) {
// body...
var self = this;
var fn = function() {
setTimeout(function() {
console.log("sleep " + time + "s ~");
self.next();
}, time * 1000);
}
this.tasks.push(fn);
//
return this;
};
_lazyman.prototype.sleepFirst = function(time) {
// body...
var self = this;
var fn = function() {
setTimeout(function() {
console.log("sleepFirst " + time + "s ~");
self.next();
}, time * 1000);
}
// unshift
this.tasks.unshift(fn);
//
return this;
};
//
function LazyMan(name) {
return new _lazyman(name);
}
호출:

LazyMan('hahah').eat('dinner').sleep(10).eat('lunch').sleepFirst(5);
// sleepFirst 10s
// hi this is hahah
// eat dinner
// sleep 10s
// eat lunch

1.체인 호출 실현 2.프로세스 제어를 실현하는 것은express의 중간부품 개념과 유사하다

좋은 웹페이지 즐겨찾기