Is Array.forEach asynchronous?


According to JavaScript, Node.js: is Array.forEach asynchronous?, Array.forEach is synchronous. However, for my code below:

function wait5() { return new Promise(resolve => setTimeout(resolve, 5000)); } async function main() { console.log("Start"); [1,2].forEach(async (e) => { const d = await wait5().then(()=> console.log("5s later") ) }) console.log("This should come last!"); } main();

The output is:

Start This should come last! 5s later 5s later

with the two "5s later" coming out in rapid succession.

Why is this the case?

If I use a normal for loop:

async function main() { console.log("Start"); for (let i=0;i<2;i++) { const d = await wait5().then(()=> console.log("5s later") ) } console.log("This should come last!"); }

then the result is what I wanted:

Start 5s later 5s later This should come last!

forEach is synchronous. Your particular callback function, however, is not. So forEach synchronously calls your function, which <em>starts</em> its work, once for each entry in the array. Later, the work that started finishes asynchronously, long after forEach has returned.

The issue is that your callback is async, not that forEach is asynchronous.

In general, when you're using an API like forEach that doesn't do anything with the return value (or doesn't expect a promise as a return value), either:


Don't pass it an async function, or

</li> <li>

Ensure that you handle errors within the function itself

</li> </ol>

Otherwise, you'll get unhandled errors if something goes wrong in the function.

Or of course:

<ol start="3"><li>Use a try/catch block within the async function to catch and handle/report errors within the function itself.</li> </ol>

It looks like you're declaring an async function inside of a caller that really doesn't care for that sort of thing, forEach. Declaring a function async makes it promise-like, but that promise is only useful if acted on.

If you need a promise-aware forEach, that's something you could implement, though Promise.each in libraries like Bluebird already do that.



  • return rows with specific tag
  • How do I get the name of the Font Family given the font file?
  • How to insert values from dynamically added rows into database
  • Double data-confirm prompt observed on rails with framework7
  • Dynamic number of ChildViewControllers for XLPagerTabStrip
  • Appending spaces with str_pad
  • Reference after posting data from web worker
  • Cannot get Django 1.7 Migrations to detect proper changes to my DB.
  • Tortoise SVN conflict occurs but no edit conflict button is shown
  • Advertising Identifier for devices lower than iOS 6.0
  • Django non-rel createsuperuser fails due to non-ascii characters
  • apache zeppelin is started but there is connection error in localhost:8080
  • Can't access web service when connected to the network :: HTTP 407
  • Determine Active Panel
  • Office.js mail object properties missing in TypeScript
  • Create One-To-One relationship between table and view in EF4?
  • Spring Cloud Config - Multiple Composite Repositories?
  • Ways of filling 10 places with number from [1..10] such that digit at ith place has value atmost 1 m
  • Get spring boot pagination number starts from 1 instead of 0
  • what do lines starting with double-slash '//' mean in a .npmrc?
  • Could not resolve all files for configuration ':react-native-vector-icons:classpath'
  • Query regarding com.jcraft.jsch.JSchException: UnknownHostKey: x.y.com. DSA key fingerprint is “ac:e
  • Boolean filter using a timestamp value on a dataframe in Python
  • css: column-count 3, image floating spanning 2, chrome not playing. why?
  • How to find angle formed by the blades of a wind turbine with respect to a horizontal imaginary axis
  • Add checkbox dynamically using angular 2
  • How to resolve this in PHPUnit where it is asking me to set KERNEL_DIR in my phpunit.xml?
  • Separating definition/instantiation of template classes without 'extern'
  • Tensorflow Dataset API restore Iterator after completing one epoch
  • Google App Engine Datastore: Dealing with eventual consistency
  • Bind selectedDates Aggregation for Calendar
  • calling IO Operations from thread in ruby c extension will cause ruby to hang
  • Call Microservice from another Microservice within Docker
  • media foundation H264 decoder not working properly