Tuesday, October 29, 2019

Array.prototype.forEach() function does not await..

Recently I discovered that Array.prototype.forEach() function is not suitable for 'awaitable' functions. Let's have a look at an example.

  1. const getAsyncData = (n) => {
  2. return new Promise((resolve, reject) => {
  3. setTimeout(() => resolve(n), 500)
  4. })
  5. };
  6. const arr = [1,2,3,4,5];
  7. //forEach example
  8. (async () => {
  9. let total = 0;
  10. arr.forEach(async n => {
  11. let res = await getAsyncData(n);
  12. console.log(res);
  13. total += res;
  14. });
  15. console.log('total = ' + total);
  16. })();
const getAsyncData = (n) => {
   return new Promise((resolve, reject) => {
      setTimeout(() => resolve(n), 500)
   })
};

const arr = [1,2,3,4,5];

//forEach example
(async () => {
   let total = 0;
   arr.forEach(async n => {
      let res = await getAsyncData(n);
      console.log(res);
      total += res;
   });
  
   console.log('total = ' + total);
})();

I expected that forEach will await for every call of the getAsyncData() function so that to calculate total correctly, but surprisingly the result was different.

total = 0
1
2
3
4
5

Obviously, forEach ignores await keyword and quits immediately so total is not calculated.