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