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

时间:2021-09-22
本文章向大家介绍for循环中有异步操作导致数据顺序错乱的问题,主要包括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]  赞~

我是一只酸菜鱼,又酸又菜又多余~~~

原文地址:https://www.cnblogs.com/liandudu/p/15318993.html