js代码实现异步同步化

咱们知道在js中同步代码永远要比步代码先执行,那么如何实现异步和同步以前执行呢?来吧~看代码
正常状况下web

let arr = [
        ()=>{
            console.log(1)
            
        },
        ()=>{
            console.log(2)
           
        
        },
        ()=>{
            setTimeout(()=>{
                console.log(3)
              
            },3000)
        },
        ()=>{            
            console.log(4)
         }       
    ]
    function zhixing (arr){
       arr.filter((item)=>{
           item() // 1 2 4 3
       })
    }
    zhixing(arr)

通过改变后:异步

let arr = [
        (next)=>{
            console.log(1)
            next()
        },
        (next)=>{
            console.log(2)
            next()
        
        },
        (next)=>{
            setTimeout(()=>{
                console.log(3)
                next()
            },3000)
        },
        (next)=>{            
            console.log(4)
         }       
    ]
    function zhixing (arr){
         let index = 0;
         let next = ()=>{
             index++;
             if(index>arr.length-1){
                 return
             }
             arr[index](next)
         }
      arr[0](next)
    }
    zhixing(arr) //最后会按顺序,打印出1,2,(3s以后打印)3,4