-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
实现一个 LazyMan #5
Labels
JavaScript
JS相关面试、笔试题,不涉及算法
Milestone
Comments
francecil
added
JavaScript
JS相关面试、笔试题,不涉及算法
and removed
JavaScript
JS相关面试、笔试题,不涉及算法
labels
Oct 10, 2019
Promise + Async链式调用时,将任务包装成一个 promise 对象并放入队列,并返回 this 代码如下 class _LazyMan {
constructor(name) {
let task = function () {
return new Promise((r) => {
console.log(`Hi! This is ${name}!`)
r()
})
}
this.callbacks = [task]
setTimeout(()=>this.flushCallback(), 0);
}
async flushCallback () {
for (let i = 0; i < this.callbacks.length; i++) {
await this.callbacks[i].call(this)
}
}
sleep (delay) {
let task = function () {
return new Promise((r) => {
setTimeout(() => {
console.log(`Wake up after ${delay}`)
r()
}, delay * 1000);
})
}
this.callbacks.push(task)
return this
}
eat (sth) {
this.callbacks.push(() => {
return new Promise((r) => {
console.log(`Eat ${sth}`)
r()
})
})
return this
}
sleepFirst (delay) {
let task = function () {
return new Promise((r) => {
setTimeout(() => {
console.log(`Wake up after ${delay}`)
r()
}, delay * 1000);
})
}
this.callbacks.unshift(task)
return this
}
}
function LazyMan(name){
return new _LazyMan(name)
} |
纯 Callback队列中存放所有任务,执行机制为:取出队头任务,执行完任务调用 next 继续取队头直到队列为空 class _LazyMan {
constructor(name) {
this.queue = [() => {
console.log(`Hi! This is ${name}!`)
this.next()
}]
setTimeout(() => this.next(), 0);
}
next () {
let task = this.queue.shift()
if (task) {
task.call(this)
}
}
sleep (delay) {
this.queue.push(() => {
setTimeout(() => {
console.log(`Wake up after ${delay}`)
this.next()
}, delay * 1000);
})
return this
}
eat (sth) {
this.queue.push(() => {
console.log(`Eat ${sth}`)
this.next()
})
return this
}
sleepFirst (delay) {
this.queue.unshift(() => {
setTimeout(() => {
console.log(`Wake up after ${delay}`)
this.next()
}, delay * 1000);
})
return this
}
}
function LazyMan (name) {
return new _LazyMan(name)
} |
拓展阅读 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
实现一个LazyMan,可以按照以下方式调用:
以此类推。
The text was updated successfully, but these errors were encountered: