实现一个js类,满足以下实现:
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
实现原理: 利用js事件循环机制,将所有方法调用按顺序压入队列中按顺序执行。中间方法的sleep利用await+async进行延时。
源码:
class LazyManClass {
constructor(name) {
this.name = name
this.tasks = []
console.log('Hi I am Tony')
setTimeout(() => {
this._interate()
}, 0)
}
eat(something) {
this.tasks.push(() => {
console.log(`I am eating ${something}`)
})
return this
}
sleep(duration) {
this.tasks.push(() => this._doSleep(duration))
return this
}
sleepFirst(duration) {
this.tasks.unshift(() => this._doSleep(duration))
return this
}
_doSleep(duration) {
return new Promise((resolve) => {
setTimeout(() => {
console.log(`等待了${duration}秒`)
resolve()
}, duration * 1000)
})
}
async _interate() {
for (const task of this.tasks) {
await task()
}
}
}
function LazyMan(name) {
return new LazyManClass(name)
}
LazyMan('Tony').eat('lunch').eat('dinner').sleepFirst(5).sleep(10).eat('junk food')