一次forEach 中 await 的使用


forEach 和 await/async 的問題

最近在刷面試提的時候看見這樣一道題

const list = [1, 2, 3]
const square = num => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(num * num)
        }, 1000)
    })
}

async function test() {
    for (const x of list) {
        const res = await square(x)
        console.log(res)
    }
}
test()
  • 問輸出什么,怎么優化間隔1秒輸出
輸出結果: 1 4 9

然后就試了了一下,同時輸出,頭疼,為什么呢? 一個大大的問號。好吧接下來找下原因吧

  • 找到問題
    看一下 forEach 實現
if (!Array.prototype.forEach) {
  Array.prototype.forEach = function(callback, thisArg) {
    var T, k;
    if (this == null) {
      throw new TypeError(' this is null or not defined');
    }

    var O = Object(this);
    var len = O.length >>> 0;

    if (typeof callback !== "function") {
      throw new TypeError(callback + ' is not a function');
    }

    if (arguments.length > 1) {
      T = thisArg;
    }
    k = 0;

    while (k < len) {
      var kValue;
      if (k in O) {
        kValue = O[k];
        callback.call(T, kValue, k, O);
      }
      k++;
    }
  };
}
// 在執行時相當於在while 中執行了異步操作
  • 解決辦法
//用for...of 或者for循環代替 forEach

async function test () {
  var nums = await getNumbers()
  for(let x of nums) {
    var res = await multi(x)
    console.log(res)
  }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM