我们知道在js中同步代码永远要比步代码先执行,那么如何实现异步和同步之前执行呢?来吧~看代码
正常情况下
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