解決await在forEach中不起作用的問題

一、前言

前兩天在項目中用for遍歷的時候遇到瞭一個坑,花瞭一天的時間解決。這裡就記一下。

二、問題

首先引一個很簡單題目:給一個數組,每隔1s打印出來.這裡我把我一開始在項目中的代碼貼出來.(當然這裡完全和業務無關的)

const _ = require('lodash');
const echo = async (i) => {
  setTimeout(() => {
    console.log('i===>', i);
  }, 5000);
}
let arrs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const task = async () => {
  _.forEach(arrs, async (i) => {
    await echo(i);
  })
}
const run = async () => {
  console.log('run-start====>date:', new Date().toLocaleDateString())
  await task() ;
  console.log('run-end====>date:', new Date().toLocaleDateString())
}
(async () => {
  console.log('start...')
  await run();
  console.log('end...')
})()
// start...
// run-start====>date: 2018-8-25
// run-end====>date: 2018-8-25
// end...
// i===> 1
// i===> 2
// i===> 3
// i===> 4
// i===> 5
// i===> 6
// i===> 7
// i===> 8
// i===> 9

上面的代碼和輸出已經給出瞭,很奇怪,這裡的await並沒有其效果.一開始因為是加瞭業務,是我的業務代碼出瞭問題,然後我就把代碼抽出來瞭,還是不起作用,當時我是真的對對await懷疑瞭。

最後還是給出問題的答案:

lodash的forEach和[].forEach不支持await,如果非要一邊遍歷一邊執行await,可使用for-of

這裡給出正確的代碼:

const _ = require('lodash');
const echo = async (i) => {
  return new Promise((resolve,reject)=>{
    setTimeout(() => {
      console.log('i===>', i,new Date().toLocaleTimeString());
      resolve(i) ;
    }, 2000);
  })
}
let arrs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const task = async () => {
  // _.forEach(arrs, async (i) => {
  //  await echo(ji) ;
  // })
  // arrs.forEach(async (i )=> {
  //   await echo(i) ;
  // });
  for (const i of arrs) {
    await echo(i) ;
  }
}
const run = async () => {
  console.log('run-start====>date:', new Date().toLocaleDateString())
  await task() ;
  console.log('run-end====>date:', new Date().toLocaleDateString())
}
(async () => {
  console.log('start...')
  await run();
  console.log('end...')
})()
// 輸出
start...
run-start====>date: 2018-8-26
i===> 1 20:51:29
i===> 2 20:51:31
i===> 3 20:51:33
i===> 4 20:51:35
i===> 5 20:51:37
i===> 6 20:51:39
i===> 7 20:51:42
i===> 8 20:51:44
i===> 9 20:51:46
i===> 10 20:51:48
run-end====>date: 2018-8-26
end...

三、總結

當解決問題的時候,有時候可以使用排除法,比方說在這個例子中,我們知道await這個機制肯定是沒問題的,如果真的有問題肯定不會輪到我測出來,那麼其實剩下來的問題隻能是for遍歷的原因瞭.

因為我一開始是用lodash實現的,那麼就可以想是不是lodash的forEach沒有作(或者做瞭多餘)await處理,此時就可以換種方式試試瞭,總的來說還是經驗的問題吧。

補充:在 forEach 中使用 async/await 遇到的問題

一、問題描述

前幾天,項目中遇到一個 JavaScript 異步問題:

有一組數據,需要對每一個數據進行一個異步處理,並且希望處理的時候是同步的。

用代碼描述如下:

// 生成數據
const getNumbers = () => {
 return Promise.resolve([1, 2, 3])
}
// 異步處理
const doMulti = num => {
 return new Promise((resolve, reject) => {
  setTimeout(() => {
   if (num) {
    resolve(num * num)
   } else {
    reject(new Error('num not specified'))
   }
  }, 2000)
 })
}
// 主函數
const main = async () => {
 console.log('start');
 const nums = [1, 2, 3];
 nums.forEach(async (x) => {
  const res = await doMulti(x);
  console.log(res);
 });
 console.log('end');
};
// 執行
main();

在這個例子中,通過 forEach 遍歷地將每一個數字都執行 doMulti 操作。代碼執行的結果是:首先會立即打印 start、end 。2 秒後,一次性輸出 1,4,9。

這個結果和我們的預期有些區別,我們是希望每間隔 2 秒,執行一次異步處理,依次輸出 1,4,9。所以當前代碼應該是並行執行瞭,而我們期望的應該是串行執行。

我們嘗試把 forEach 循環替換成 for 循環:

const main = async () => {
 console.log('start');
 const nums = await getNumbers();
 for (const x of nums) {
  const res = await doMulti(x);
  console.log(res);
 }
 console.log('end');
};

執行結果完全符合瞭預期:依次輸出:start、1, 4, 9, end 。

二、問題分析

思路都是一樣的,隻是使用的遍歷方式不一樣而已,為什麼會出現這樣的情況呢?在 MDN 上查找瞭一下 forEach 的 polyfill 參考 MDN-Array.prototype.forEach() :

// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.io/#x15.4.4.18
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');
  }
  // 1. Let O be the result of calling toObject() passing the
  // |this| value as the argument.
  var O = Object(this);
  // 2. Let lenValue be the result of calling the Get() internal
  // method of O with the argument "length".
  // 3. Let len be toUint32(lenValue).
  var len = O.length >>> 0;
  // 4. If isCallable(callback) is false, throw a TypeError exception. 
  // See: http://es5.github.com/#x9.11
  if (typeof callback !== "function") {
   throw new TypeError(callback + ' is not a function');
  }
  // 5. If thisArg was supplied, let T be thisArg; else let
  // T be undefined.
  if (arguments.length > 1) {
   T = thisArg;
  }
  // 6. Let k be 0
  k = 0;
  // 7. Repeat, while k < len
  while (k < len) {
   var kValue;
   // a. Let Pk be ToString(k).
   //  This is implicit for LHS operands of the in operator
   // b. Let kPresent be the result of calling the HasProperty
   //  internal method of O with argument Pk.
   //  This step can be combined with c
   // c. If kPresent is true, then
   if (k in O) {
    // i. Let kValue be the result of calling the Get internal
    // method of O with argument Pk.
    kValue = O[k];
    // ii. Call the Call internal method of callback with T as
    // the this value and argument list containing kValue, k, and O.
    callback.call(T, kValue, k, O);
   }
   // d. Increase k by 1.
   k++;
  }
  // 8. return undefined
 };
}

從上面的 polyfill 中的 setp 7 ,我們可以簡單地理解成下面的步驟:

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 循環執行瞭這個異步函數,所以是並行執行,導致瞭一次性全部輸出結果:1,4,9 。

const main = async () => {
 console.log('start');
 const nums = await getNumbers();
 // nums.forEach(async (x) => {
 //  const res = await doMulti(x);
 //  console.log(res);
 // });
 for (let index = 0; index < nums.length; index++) {
  (async x => {
   const res = await doMulti(x)
   console.log(res)
  })(nums[index])
 }
 console.log('end');
};

三、解決方案

現在,我們把問題分析清楚瞭。前面用 for-of 循環來代替 forEach 作為解決方案 ,其實我們也可以改造一下 forEach :

const asyncForEach = async (array, callback) => {
 for (let index = 0; index < array.length; index++) {
  await callback(array[index], index, array);
 }
}
const main = async () => {
 console.log('start');
 const nums = await getNumbers();
 await asyncForEach(nums, async x => {
  const res = await doMulti(x)
  console.log(res)
 })
 console.log('end');
};
main();

四、Eslint 問題

這時候 Eslint 又報瞭錯:no-await-in-loop 。關於這一點,Eslint 官方文檔 https://eslint.org/docs/rules/no-await-in-loop 也做瞭說明。

好的寫法:

async function foo(things) {
 const results = [];
 for (const thing of things) {
  // Good: all asynchronous operations are immediately started.
  results.push(bar(thing));
 }
 // Now that all the asynchronous operations are running, here we wait until they all complete.
 return baz(await Promise.all(results));
}

不好的寫法:

async function foo(things) {
 const results = [];
 for (const thing of things) {
  // Bad: each loop iteration is delayed until the entire asynchronous operation completes
  results.push(await bar(thing));
 }
 return baz(results);
}

其實上面兩種寫法沒有什麼好壞之分,這兩種寫法的結果是完全不一樣的。Eslint 推薦的 “好的寫法” 在執行異步操作的時候沒有順序的,“不好的寫法” 中有順序,具體需要用哪種寫法還是要根據業務需求來決定。

所以,在文檔的 When Not To Use It 中,Eslint 也提到,如果需要有順序地執行,我們是可以禁止掉該規則的:

In many cases the iterations of a loop are not actually independent of each-other. For example, the output of one iteration might be used as the input to another. Or, loops may be used to retry asynchronous operations that were unsuccessful. Or, loops may be used to prevent your code from sending an excessive amount of requests in parallel. In such cases it makes sense to use await within a loop and it is recommended to disable the rule via a standard ESLint disable comment.

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。如有錯誤或未考慮完全的地方,望不吝賜教。

推薦閱讀: