在阅读vue-router源码的时候接触了这个异步函数队列化执行的设计,感觉还是挺厉害的,在此做个总结:
let runQueue = (queue, fn, cb) => {
const step = (index) => {
if(index >= queue.length) {
cb()
}else {
if(queue[index]) {
fn(queue[index], () => {
step(index + 1)
})
}else {
step(index + 1)
}
}
}
step(0)
}
const iterator = (fn, next) => {
fn(() => {
next()
})
}
let f1 = (resolve) => {
console.log('this is f1');
resolve()
}
let f2 = (resolve) => {
setTimeout(function() {
console.log('this is f2')
resolve();
}, 1000)
}
let f3 = (resolve) => {
console.log('this is f3');
resolve();
}
let myQueue = [];
myQueue.push(f1)
myQueue.push(f2)
myQueue.push(f3)
let myCb = () => {
console.log('all is done')
}
runQueue(myQueue, iterator, myCb)
// this is f1
// this is f2
// this is f3
// all is done
网友评论