zoukankan      html  css  js  c++  java
  • 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或函数。

    我站在山顶看风景!下面是我的家乡!
  • 相关阅读:
    leetcode1118
    Kaggle练习002--Predict survival on the Titanic(Titanic Disaster)
    leetcode1111
    leetcode1110
    leetcode1109
    练习题|网络编程-socket开发
    web网页练习
    Bootstrap框架
    JQuery框架2.位置属性|筛选方法|事件
    Jquery框架1.选择器|效果图|属性、文档操作
  • 原文地址:https://www.cnblogs.com/zhensg123/p/14725672.html
Copyright © 2011-2022 走看看