for循环中有异步操作导致数据顺序错乱的问题


经常会遇到for循环里有异步操作,比如某些条件下要去请求数据,某些条件下只是静态数据。最终得到的结果和预期的不一致。

function Func () {
  let tempArr = []
  for (let i = 0; i < 10; i++) {
    if (i % 2 == 0) {
      tempArr.push(i + 10)
    } else {
      //  setTimeout 模拟遇到的异步操作
      setTimeout(() => {
        tempArr.push(i)
      }, 1)
    }
  }
  console.log(56, tempArr)
}
Func()

我们期望的结果是按照循环顺序的数据结果:[10, 1, 12, 3, 14, 5, 16, 7, 18, 9]

但实际输出:异步的结果被追加在了静态数据之后

 

那么应该如何获取想要的顺序呢?其实很简单,promise 搞定

async function Func () {
  let tempArr = []
  for (let i = 0; i < 10; i++) {
    if (i % 2 == 0) {
      tempArr.push(i + 10)
    } else {
      await this.asyncFunc(tempArr, i)
    }
  }
  console.log(56, tempArr)
}
function asyncFunc (tempArr, i) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      tempArr.push(i)
      // 在异步中将结果返回
      resolve()
    }, 1)
  })
}

最终结果:[10, 1, 12, 3, 14, 5, 16, 7, 18, 9]  赞~

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM