forEach 和 await/async 的問題


最近在用node寫一個靜態文件服務器的時候遇到了一個問題,在forEach循環里面調用await/async異步函數的問題。 這個問題也遇到幾次了,這里記下避免下次再忘。

問題重現

var getNumbers = () => {
  return Promise.resolve([1, 2, 3])
}

var multi = num => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (num) {
        resolve(num * num)
      } else {
        reject(new Error('num not specified'))
      }
    }, 1000)
  })
}

async function test () {
  var nums = await getNumbers()
  nums.forEach(async x => {
    var res = await multi(x)
    console.log(res)
  })
}

test()

在test 函數執行后我期望的結果是代碼是串行執行的,我會在每等一秒鍾輸出一個數 ...1 ...4 ...9,但是現在獲得的結果是等了一秒一起輸出結果 1 4 9

找到問題

為什么在for循環/ for...of 里面可以實現await/async的功能,但是在forEach里面就不可以呢?首先我們來看下MDN網站的Polyfill

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++;
    }
  };
}

可以看到當我們在forEach里面寫的callback函數會直接在while循環里面調用,簡化下

Array.prototype.forEach = function (callback) {
  // this represents our array
  for (let index = 0; index < this.length; index++) {
    // We call the callback for each entry
    callback(this[index], index, this)
  }
}

相當於在for循環中執行了異步函數

async function test () {
  var nums = await getNumbers()
//   nums.forEach(async x => {
//     var res = await multi(x)
//     console.log(res)
//   })
  for(let index = 0; index < nums.length; index++) {
    (async x => {
      var res = await multi(x)
      console.log(res)
    })(nums[index])
  }
}

解決辦法

用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