实现一个可链式调用并可sleep
的LazyMan
class LazyMan {
constructor(name) {
// 保存要执行的任务
this.tasks = [];
// 初始化中先push一个task
const task = () => {
console.log(`hi this is ${name}`);
// 执行下一个task
this.next();
};
this.tasks.push(task);
// 添加到宏队列中就保证了,在执行的时候tak都已经放在taks里面了
setTimeout(() => {
this.next();
}, 0);
}
next() {
// console.log('this.tasks', this.tasks);
const task = this.tasks.shift();
task && task();
}
eat(name) {
const task = () => {
console.log(`eat ${name}`);
this.next();
};
this.tasks.push(task);
return this;
}
sleep(time) {
const task = () => {
setTimeout(() => {
console.log(`sleep ${time} h`);
this.next();
}, time);
};
this.tasks.push(task);
return this;
}
}
const lazyMan = new LazyMan('th');
lazyMan.sleep(12).eat('酸菜鱼');
/*
hi this is th
sleep 12 h
eat 酸菜鱼
*/