• promise顺序执行的多种方案


    异步管理一直是前端开发的一个重点。

    就多个promise的顺序执行,总结了下面几种方案。

    使用回调的方案,也是最传统的方案

    const f1 = ()=>new Promise((resolve, reject)=>{
               setTimeout(()=>{
                   console.log('p1 runing')
                   resolve(1)
               }, 1000)
            })
    
            const f2 = ()=>new Promise((resolve, reject)=>{
               setTimeout(()=>{
                   console.log('p2 runing')
                   resolve(2)
               }, 1000)
            })
    
            // 使用回调形式
            f1().then(()=>{
                f2()
            })
    

     使用async、await的方案。

            // 使用async await
            async function asyncPromise(){
                await f1()
                f2()
            }
    

      使用reduce的方案,认为是最为优雅,但是最为难懂的。

            const arr = [f1, f2]
            const runPromiseInsequence = (array, value)=>array.reduce(
                (promiseChain, currentFunction)=>promiseChain.then(currentFunction),
                Promise.resolve(value)
            )
            runPromiseInsequence(arr, 'init')
    

      使用递归的方案

    // 使用递归
            const arr = [f1, f2]
            function sequencePromise(arr){
               const pro = arr.shift()
               if(pro) {
                pro().then(()=>{
                    sequencePromise(arr)
                   })
               }
            }
            sequencePromise(arr)

    以上四种,后两种可以不增加代码的情况就可以直接顺序执行多个promise。

    而我把传统的和最后一种作为母本方案:作为典型的解决方案。

    这几天一个心得:探索新的解决方案是很好的拓展知识的手段。主动的探索方法可以是多问几个为什么,有什么好处,以及尝试其它解决方案。针对方法可以考虑参数为Promise或函数。

    我站在山顶看风景!下面是我的家乡!
  • 相关阅读:
    《道德经》全文
    mysql 服务启动后停止
    安装docker-compose
    金刚般若波罗蜜经
    elasticsearch reIndex
    【基础篇】1.vim复制黏贴跳转
    新事物如何持续性发展
    舒服的状态
    教父
    关于拖延
  • 原文地址:https://www.cnblogs.com/zhensg123/p/14725672.html
Copyright © 2020-2023  润新知