{"id":1937,"date":"2022-01-16T10:45:29","date_gmt":"2022-01-16T16:45:29","guid":{"rendered":"https:\/\/www.becomebetterprogrammer.com\/?p=1937"},"modified":"2022-04-25T09:36:44","modified_gmt":"2022-04-25T14:36:44","slug":"javascript-foreach-async-await","status":"publish","type":"post","link":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-foreach-async-await\/","title":{"rendered":"Understand JavaScript forEach() Behavior with async\/await"},"content":{"rendered":"\n<p>JavaScript is often one of the first programming languages new programmers use not only due to its popularity and high demand but also because it offers flexibility to use a mixture of object-oriented programming and functional programming. Unfortunately, that flexibility can lead to problems that are not easy to identify such as the hidden problems of using <code>Array.forEach()<\/code> method to run asynchronous code.<\/p>\n\n\n\n<p>Programmers use the <code>forEach<\/code> method to loop through each of the elements of an array to execute the same process. Unfortunately, <strong>the <code>forEach<\/code> method wasn&#8217;t meant to execute asynchronous callback functions, even though it is possible to use the keywords <code>async<\/code> and <code>await<\/code> with it<\/strong>. <\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_82_2 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\"><p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<\/div><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-foreach-async-await\/#Why_is_ArrayforEach_not_meant_for_asynchronous_programming\" >Why is Array.forEach() not meant for asynchronous programming?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-foreach-async-await\/#Why_ArrayforEach_with_asyncawait_does_not_actually_wait\" >Why Array.forEach() with async\/await does not actually wait?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-foreach-async-await\/#Alternative_solutions_to_running_asynchronous_code_in_a_loop\" >Alternative solutions to running asynchronous code in a loop<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-foreach-async-await\/#Using_traditional_for_loop_for_sequential_executions\" >Using traditional for loop for sequential executions<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-foreach-async-await\/#Using_for_of_loop_for_sequential_executions\" >Using for ... of loop for sequential executions<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-foreach-async-await\/#Using_Promiseall_and_Arraymap_for_concurrent_executions_Recommended\" >Using Promise.all and Array.map() for concurrent executions (Recommended)<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-foreach-async-await\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Why_is_ArrayforEach_not_meant_for_asynchronous_programming\"><\/span>Why is Array.forEach() not meant for asynchronous programming?  <span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Looking for an answer explaining why the <code>forEach<\/code> doesn&#8217;t work as expected when using it with <code>async<\/code> and <code>await<\/code> keywords is rather complex.<\/p>\n\n\n\n<p>If we verify the Mozilla MZN Web documentation and read through the <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Array\/forEach\" target=\"_blank\" rel=\"noreferrer noopener\">Array.prototype.forEach()<\/a> reference, you will find out there is a note saying <strong>forEach expects a synchronous function<\/strong>. While this site has become one of the main documentation references for JavaScript programmers, in theory, it is not the official documentation despite their excellent way to explain the concepts.<\/p>\n\n\n\n<p>The official documentation for JavaScript is defined by <a href=\"https:\/\/tc39.es\/\" target=\"_blank\" rel=\"noreferrer noopener\">Ecma International&#8217;s TC39<\/a>, a group of JavaScript developers collaborating with the community to maintain and evolve the definition of JavaScript. <\/p>\n\n\n\n<p>If we take a look at <a href=\"https:\/\/tc39.es\/ecma262\/multipage\/indexed-collections.html#sec-array.prototype.foreach\" target=\"_blank\" rel=\"noreferrer noopener\">ECMA specifications defining the Array.forEach<\/a> method, it doesn&#8217;t say anything about the method not designed for asynchronous operations.<\/p>\n\n\n\n<p><em>If it is not in the documentation, why do you claim it is not meant for asynchronous programming?<\/em><\/p>\n\n\n\n<p>This is when JavaScript shows one of those unexpected behaviors only developers who have noticed it, can share and advise to not use the <code>forEach<\/code> method with <code>async<\/code> and <code>await<\/code> because it doesn&#8217;t &#8220;await&#8221; or wait for a process to finish prior to continuing to the next process inside the callback function.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Why_ArrayforEach_with_asyncawait_does_not_actually_wait\"><\/span>Why Array.forEach() with async\/await does not actually wait?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Unless we have access to inspect the definition of the <code>forEach<\/code> method and understand what goes on behind, one way is to see an example of what happens when attempting to use <code>forEach<\/code> with <code>async<\/code> and <code>await<\/code>.<\/p>\n\n\n\n<p>Let&#8217;s take a look at the following example and check a typical developer writing asynchronous logic inside the <code>forEach<\/code> callback without knowing the hidden problem he will face. For reference purposes, we are going to say this code is stored in the test.js file.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>async function displayValuesWithWait(value) {\n  return new Promise((resolve) =&gt; {\n    setTimeout(() =&gt; {\n      console.log(\"The current value is: \", value);\n      resolve();\n    }, 1000);\n  });\n}\n\nasync function valueLogger() {\n  const values = &#91;1, 2, 3, 4, 5];\n\n  console.log(\"Starting to display values\");\n\n  values.forEach(async (value) =&gt; {\n\n    console.log('About to run displayValuesWithWait() process for value ', value);\n\n    await displayValuesWithWait(value);\n\n    console.log('Finished displayValuesWithWait() for value ', value);\n  });\n\n  console.log(\"Finished displaying values\");\n}\n\nvalueLogger();<\/code><\/pre>\n\n\n\n<p>If you noticed, the <code>valueLogger<\/code> function has an array of <code>values<\/code> which uses the <code>forEach<\/code> method to trigger <code>displayValuesWithWait<\/code> asynchronous function. Also, there is a series of logs generated throughout the code to show what is actually being triggered when the code is executed.<\/p>\n\n\n\n<p>The developer most likely expects the following sequence of logs once the code is run:<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>Starting to display values\nAbout to run displayValuesWithWait() process for value 1\nThe current value is: 1\nFinished displayValuesWithWait() for value 1\nAbout to run displayValuesWithWait() process for value 2\nThe current value is: 2\nFinished displayValuesWithWait() for value 2\nAbout to run displayValuesWithWait() process for value 3\nThe current value is: 3\nFinished displayValuesWithWait() for value 3\nAbout to run displayValuesWithWait() process for value 4\nThe current value is: 4\nFinished displayValuesWithWait() for value 4\nAbout to run displayValuesWithWait() process for value 5\nThe current value is: 5\nFinished displayValuesWithWait() for value 5\nFinished displaying values<\/code><\/pre>\n\n\n\n<p>If we run the code using the following command (feel free to create a test.js file and execute the code),<\/p>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>node test<\/code><\/pre>\n\n\n\n<p>we get the following output in the terminal<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"431\" height=\"305\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2022\/01\/Result-after-executing-test.js-code-1.png\" alt=\"\" class=\"wp-image-1939\" title=\"Result after executing test.js code\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/01\/Result-after-executing-test.js-code-1.png 431w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/01\/Result-after-executing-test.js-code-1-300x212.png 300w\" sizes=\"auto, (max-width: 431px) 100vw, 431px\" \/><figcaption>Result after executing test.js code<\/figcaption><\/figure><\/div>\n\n\n\n<p>N<em>otice how the log &#8220;Finished displaying values&#8221;<\/em> is displayed before any of the<em> <\/em>&#8220;The current value is:&#8221; logs are displayed. <\/p>\n\n\n\n<p><strong>Why?<\/strong><\/p>\n\n\n\n<p>One person might say after inspecting the code, the <code>displayValuesWithWait<\/code> function waits one second to log the value <em>&#8220;The current value is:&#8221;<\/em>, suggesting that as the reason the <span style=\"text-decoration: underline;\"><em>&#8220;The current value is:&#8221;<\/em><\/span> logs are displayed in the end. <\/p>\n\n\n\n<p>However, using <code>async<\/code> and <code>await<\/code> keywords to trigger <code>displayValuesWithWait<\/code> implies waiting for the asynchronous function to finish prior to continuing to the next process like it is defined inside the <code>forEach<\/code> callback function.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>    console.log('About to run displayValuesWithWait() process for value ', value);\n\n    await displayValuesWithWait(value);\n\n    console.log('Finished displayValuesWithWait() for value ', value);<\/code><\/pre>\n\n\n\n<p>Even if we modify the <code>displayValuesWithWait<\/code> function and make it simpler, such as removing the promise definition, the usage of the <code>setTimeout<\/code> and even the <code>async<\/code> keyword from the function definition.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>function displayValuesWithWait(value) {\n  console.log(\"The current value is: \", value);\n}<\/code><\/pre>\n\n\n\n<p>Notice we haven&#8217;t made changes to the <code>forEach<\/code> callback function yet.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>values.forEach(async (value) =&gt; {\n    console.log('About to run displayValuesWithWait() process for value ', value);\n\n    await displayValuesWithWait(value);\n\n    console.log('Finished displayValuesWithWait() for value ', value);\n  });<\/code><\/pre>\n\n\n\n<p>If we attempt to run the code, this is the result we get:<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"417\" height=\"296\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2022\/01\/Result-after-executing-test.js-code-with-modified-displayValuesWithWait-function-1.png\" alt=\"\" class=\"wp-image-1941\" title=\"Result after executing test.js code with modified displayValuesWithWait function\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/01\/Result-after-executing-test.js-code-with-modified-displayValuesWithWait-function-1.png 417w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/01\/Result-after-executing-test.js-code-with-modified-displayValuesWithWait-function-1-300x213.png 300w\" sizes=\"auto, (max-width: 417px) 100vw, 417px\" \/><figcaption>Result after executing test.js code with modified displayValuesWithWait function<\/figcaption><\/figure><\/div>\n\n\n\n<p>Notice how we still get unexpected results. This time getting all the <em>&#8220;Finished displayValuesWithWait() for value&#8221;<\/em> logs in the end.<\/p>\n\n\n\n<p>Therefore, the loop finishes before all the callback function processes finish when using <code>forEach <\/code>with the <code>async<\/code> keyword. The <code>await<\/code> keyword doesn&#8217;t wait before executing the next process.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Alternative_solutions_to_running_asynchronous_code_in_a_loop\"><\/span>Alternative solutions to running asynchronous code in a loop<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Using_traditional_for_loop_for_sequential_executions\"><\/span>Using traditional <code>for<\/code> loop for sequential executions<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Using a traditional <code>for(\u2026;\u2026;\u2026)<\/code> loop works with asynchronous operations. This solution is recommended if we want to preserve the order of operations in sequential order. We can quickly verify this by tweaking the <code>valueLogger<\/code> logic to use a <code>for<\/code> loop. <\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>function displayValuesWithWait(value) {\n  console.log(\"The current value is: \", value);\n}\n\nasync function valueLogger() {\n  const values = &#91;1, 2, 3, 4, 5];\n\n  console.log(\"Starting to display values\");\n\n  for (let i = 0; i &lt; values.length; i++) {\n    const value = values&#91;i];\n    console.log(\n      \"About to run displayValuesWithWait() process for value \",\n      value\n    );\n\n    await displayValuesWithWait(value);\n\n    console.log(\"Finished displayValuesWithWait() for value \", value);\n  }\n\n  console.log(\"Finished displaying values\");\n}\n\nvalueLogger();<\/code><\/pre>\n\n\n\n<p>Running the updated logic will output the following logs in the terminal:<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2022\/01\/Correct-expected-result-after-executing-test.js-code.png\" alt=\"\" class=\"wp-image-1943\" width=\"429\" height=\"302\" title=\"Correct expected result after executing test.js code\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/01\/Correct-expected-result-after-executing-test.js-code.png 429w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/01\/Correct-expected-result-after-executing-test.js-code-300x211.png 300w\" sizes=\"auto, (max-width: 429px) 100vw, 429px\" \/><figcaption>The correct expected result after executing test.js code<\/figcaption><\/figure><\/div>\n\n\n\n<p>Finally, we are getting the correct expected result from what we originally intended to execute with our first version of the <code>valueLogger<\/code> code.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Using_for_of_loop_for_sequential_executions\"><\/span>Using <code>for ... of<\/code> loop for sequential executions<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Another option is to use the alternative version of the <code>for<\/code> loop (<code>for ... of<\/code>).<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>function displayValuesWithWait(value) {\n  console.log(\"The current value is: \", value);\n}\n\nasync function valueLogger() {\n  const values = &#91;1, 2, 3, 4, 5];\n\n  console.log(\"Starting to display values\");\n\n  for (const value of values) {\n    console.log(\n      \"About to run displayValuesWithWait() process for value \",\n      value\n    );\n\n    await displayValuesWithWait(value);\n\n    console.log(\"Finished displayValuesWithWait() for value \", value);\n  }\n\n  console.log(\"Finished displaying values\");\n}\n\nvalueLogger();<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Using_Promiseall_and_Arraymap_for_concurrent_executions_Recommended\"><\/span>Using <code>Promise.all<\/code> and <code>Array.map()<\/code> for concurrent executions (Recommended)<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>It is possible to use <code>Array.map()<\/code> method to get an array of promises and execute all promises using <code>Promise.all<\/code>. <strong>Using <code>Promise.all<\/code> with <code>Array.map()<\/code> is recommended if we want to concurrently execute asynchronous code for each element in an array.<\/strong> Hence, improving the performance of the code.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>function displayValuesWithWait(value) {\n  console.log(\"The current value is: \", value);\n}\n\nasync function valueLogger() {\n  const values = &#91;1, 2, 3, 4, 5]\n\n  console.log(\"Starting to display values\");\n\n  await Promise.all(\n    values.map(async (value) =&gt; {\n      console.log(\n        \"About to run displayValuesWithWait() process for value \",\n        value\n      );\n\n      await displayValuesWithWait(value);\n\n      console.log(\"Finished displayValuesWithWait() for value \", value);\n    })\n  );\n\n  console.log(\"Finished displaying values\");\n}\n\nvalueLogger();<\/code><\/pre>\n\n\n\n<p>Checking the logs from running the previous example will help us understand why the code is run concurrently.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"438\" height=\"306\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2022\/01\/Result-after-using-Promise.all-and-array.map-function.png\" alt=\"\" class=\"wp-image-1944\" title=\"Result after using Promise.all and array.map function\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/01\/Result-after-using-Promise.all-and-array.map-function.png 438w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/01\/Result-after-using-Promise.all-and-array.map-function-300x210.png 300w\" sizes=\"auto, (max-width: 438px) 100vw, 438px\" \/><figcaption>Result after using Promise.all and array.map function<\/figcaption><\/figure><\/div>\n\n\n\n<p>Notice how the<strong> logs are not in sequential order<\/strong>. If the logs were in sequential order, we would have seen a result like this: <\/p>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>About to run displayValuesWithWait() process for value  1\nThe current value is:  1\nFinished displayValuesWithWait() for value  1\nAbout to run displayValuesWithWait() process for value  2\nThe current value is:  2\nFinished displayValuesWithWait() for value  2<\/code><\/pre>\n\n\n\n<p>To make it even more clear the &#8220;concurrent&#8221; concept, we are tweaking the <code>displayValuesWithWait<\/code> function to use a timeout at random times.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>async function displayValuesWithWait(value) {\n  \/\/ use the alternative wait to explain concurrent\n  const wait = Math.floor(Math.random() * 2) * 1000;\n\n  return new Promise((resolve) =&gt; {\n    setTimeout(() =&gt; {\n      console.log(\"The current value is: \", value);\n      resolve();\n    }, wait);\n  });\n}\n\nasync function valueLogger() {\n  const values = &#91;1, 2, 3, 4, 5];\n\n  console.log(\"Starting to display values\");\n\n  await Promise.all(\n    values.map(async (value) =&gt; {\n      console.log(\n        \"About to run displayValuesWithWait() process for value \",\n        value\n      );\n\n      await displayValuesWithWait(value);\n\n      console.log(\"Finished displayValuesWithWait() for value \", value);\n    })\n  );\n\n  console.log(\"Finished displaying values\");\n}\n\nvalueLogger();<\/code><\/pre>\n\n\n\n<p>After running the code, notice how the values of the array are not logged in the correct order. However, the processes executed per each element of the array finish before displaying the <em>&#8220;Finished displaying values<\/em>&#8221; log.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"440\" height=\"311\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2022\/01\/Another-example-of-Promise.all-with-array.map-showing-the-concurrent-behavior.png\" alt=\"\" class=\"wp-image-1945\" title=\"Another example of Promise.all with array.map showing the concurrent behavior\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/01\/Another-example-of-Promise.all-with-array.map-showing-the-concurrent-behavior.png 440w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/01\/Another-example-of-Promise.all-with-array.map-showing-the-concurrent-behavior-300x212.png 300w\" sizes=\"auto, (max-width: 440px) 100vw, 440px\" \/><figcaption>Another example of Promise.all with array.map showing the concurrent behavior<\/figcaption><\/figure><\/div>\n\n\n\n<p><strong>Note<\/strong>: Using the map function by itself won&#8217;t allow the asynchronous code to wait when using the <code>await<\/code> keyword. The following example will behave similarly to how asynchronous code is written using the <code>forEach<\/code> function.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>function displayValuesWithWait(value) {\n  console.log(\"The current value is: \", value);\n}\n\nasync function valueLogger() {\n  const values = &#91;1, 2, 3, 4, 5];\n\n  console.log(\"Starting to display values\");\n\n  values.map(async (value) =&gt; {\n    console.log(\n      \"About to run displayValuesWithWait() process for value \",\n      value\n    );\n\n    await displayValuesWithWait(value);\n\n    console.log(\"Finished displayValuesWithWait() for value \", value);\n  });\n\n  console.log(\"Finished displaying values\");\n}\n\nvalueLogger();\n\n<\/code><\/pre>\n\n\n\n<p>The result from running the previous snippet of code is not what we are expecting.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"417\" height=\"296\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2022\/01\/Result-after-executing-test.js-code-with-modified-displayValuesWithWait-function-1.png\" alt=\"\" class=\"wp-image-1941\" title=\"Result after executing test.js code using the array.map function\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/01\/Result-after-executing-test.js-code-with-modified-displayValuesWithWait-function-1.png 417w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/01\/Result-after-executing-test.js-code-with-modified-displayValuesWithWait-function-1-300x213.png 300w\" sizes=\"auto, (max-width: 417px) 100vw, 417px\" \/><figcaption>Result after executing test.js code using the array.map function<\/figcaption><\/figure><\/div>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>All in all, JavaScript <code>forEach<\/code> function executes code synchronously regardless of using it with or without the async and await keywords, which are meant to run code asynchronously. Using <code>forEach<\/code> with asynchronous code doesn&#8217;t mean the code will not run. However, it will run with unexpected behaviors.<\/p>\n\n\n\n<p>Fortunately, there are solutions to run asynchronous code for all the items of an array such as using traditional JavaScript loops (<code>for (...;...;...)<\/code> or <code>for ... of<\/code>) for sequential executions,  or combining <code>Promise.all<\/code> with <code>array.map()<\/code> for concurrent executions.<\/p>\n\n\n\n<p><strong>Did you like this article?<\/strong><\/p>\n\n\n\n<p>Share your thoughts by replying on <a href=\"https:\/\/twitter.com\/bbprogrammer\" target=\"_blank\" rel=\"noreferrer noopener\">Twitter of Become A Better Programmer<\/a> or to my<a href=\"https:\/\/twitter.com\/arealesramirez\" target=\"_blank\" rel=\"noreferrer noopener\"> personal Twitter account<\/a>.<\/p>\n\n\n\n<figure class=\"wp-block-embed aligncenter is-type-rich is-provider-twitter wp-block-embed-twitter\"><div class=\"wp-block-embed__wrapper\">\nhttps:\/\/twitter.com\/bbprogrammer\/status\/1482756688751038467\n<\/div><\/figure>\n","protected":false},"excerpt":{"rendered":"<p>Learn why the forEach() function doesn&#8217;t &#8220;wait&#8221; code to execute when using it with async\/await. Learn solutions for asynchronous code in JavaScript using loops<\/p>\n","protected":false},"author":1,"featured_media":1948,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"nf_dc_page":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[16],"tags":[],"class_list":["post-1937","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-javascript","generate-columns","tablet-grid-50","mobile-grid-100","grid-parent","grid-50"],"_links":{"self":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/1937","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/comments?post=1937"}],"version-history":[{"count":5,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/1937\/revisions"}],"predecessor-version":[{"id":2463,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/1937\/revisions\/2463"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media\/1948"}],"wp:attachment":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media?parent=1937"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/categories?post=1937"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/tags?post=1937"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}