美文网首页
异步函数队列化执行总结

异步函数队列化执行总结

作者: 李牧敲代码 | 来源:发表于2020-04-15 11:01 被阅读0次

    在阅读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
    

    相关文章

      网友评论

          本文标题:异步函数队列化执行总结

          本文链接:https://www.haomeiwen.com/subject/bcwqvhtx.html