Open MrSeaWave opened 3 years ago
class LazyManCl {
constructor(name) {
this._queue = [];
this._init(name);
}
_init(name) {
console.log(`I'm ${name}`);
// 主任务都执行完毕后开始执行第一次
Promise.resolve().then(() => {
console.log('12');
this._next();
});
}
eat(str) {
this._queue.push(() => {
console.log(`I am eating ${str}`);
this._next();
});
return this;
}
sleep(time) {
this._queue.push(() => {
this._sleep(time).then(() => {
console.log(`等待了${time}秒...`);
this._next();
});
});
return this;
}
sleepFirst(time) {
this._queue.unshift(() => {
this._sleep(time).then(() => {
console.log(`等待了${time}秒...`);
this._next();
});
});
return this;
}
_sleep(time) {
return new Promise((resolve) => setTimeout(resolve, time * 1000));
}
_next() {
const fn = this._queue.shift();
fn && fn();
}
}
function LazyMan(name) {
return new LazyManCl(name);
}
LazyMan('Tony');
// Hi I am Tony
LazyMan('Tony').sleep(10).eat('lunch');
// Hi I am Tony
// 等待了10秒...
// I am eating lunch
LazyMan('Tony').eat('lunch').sleep(10).eat('dinner');
// Hi I am Tony
// I am eating lunch
// 等待了10秒...
// I am eating diner
LazyMan('Tony')
.eat('lunch')
.eat('dinner')
.sleepFirst(5)
.sleep(10)
.eat('junk food');
// // Hi I am Tony
// // 等待了5秒...
// // I am eating lunch
// // I am eating dinner
// // 等待了10秒...
// // I am eating junk food
class LazyManClass {
constructor(name) {
this.name = name;
console.log("Hi, I'm ", name);
this.queue = [];
setTimeout(() => this.run(), 0);
}
async run() {
console.log('this.queue', this.queue);
for (let i = 0; i < this.queue.length; i++) {
await this.queue[i]();
}
}
sleep(time) {
this.queue.push(async () => {
console.log(`等待了${time}s`);
await this._sleep(time);
});
return this;
}
eat(str) {
this.queue.push(() => {
console.log(`I am eating ${str}`);
});
return this;
}
sleepFirst(time) {
this.queue.unshift(async () => {
console.log(`等待了${time}s`);
await this._sleep(time);
});
return this;
}
_sleep(time) {
return new Promise((resolve) => {
setTimeout(resolve, time * 1000);
});
}
}
function LazyMan(name) {
return new LazyManClass(name);
}
// LazyMan('Tony').sleep(10).eat('lunch');
LazyMan('Tony')
.eat('lunch')
.eat('dinner')
.sleepFirst(5)
.sleep(10)
.eat('junk food');
class LazyManCls {
constructor(name) {
console.log(`Hi I am ${name}`);
this.queue = [];
this._run();
}
_run() {
Promise.resolve().then(async () => {
for (let i in this.queue) {
await this.queue[i]();
}
});
}
eat(type) {
this.queue.push(() => {
console.log(`I am eating ${type}`);
});
return this;
}
sleep(time) {
this.queue.push(() => {
return this._sleep(time);
});
return this;
}
sleepFirst(time) {
this.queue.unshift(() => {
return this._sleep(time);
});
return this;
}
_sleep(time) {
return new Promise((resolve) => {
console.log(`等待了 ${time} 秒`);
setTimeout(resolve, time * 1000);
});
}
}
function LazyMan(name) {
return new LazyManCls(name);
}