let index = 0
let stack = []
function next(){
let fn = stack[index]
index++
if(typeof fn === 'function') {
fn()
}
}
function T(name) {
stack.push(function() {
console.log('Hi! This is' + name)
next()
})
}
function task(name) {
return new T(name)
}
T.prototype.sleep = function(delay) {
stack.push(function() {
setTimeout(() => {
console.log('sleep have run end')
next()
},delay)
})
return this
}
T.prototype.eat = function() {
stack.push(function() {
console.log('eat have run end')
next()
})
return this
}
task('zhangsan').sleep(1000).eat().sleep(1000).eat()
next()
JS函数链式调用,实现一下task().eat().sleep(2000).eat().sleep(2000)函数
最新推荐文章于 2022-11-03 11:30:27 发布
本文介绍了一个通过函数堆栈实现异步任务调度的编程模型,展示了如何使用`task`、`sleep`和`eat`方法配合延迟和事件循环,模拟了ZhangSan依次执行睡眠和吃饭操作。

212

被折叠的 条评论
为什么被折叠?



