Wait ... snooze in forEach loop

should this code return 12334 or 12433?

I expect 12334, but it gives 12433 ...

console.log '1'
anArray.forEach (info, index, array)->
  console.log '2'

  await model.findOne info, defer(err, doc)
  console.log '3'

console.log '4'
+3
source share
1 answer

Your intuition is incorrect: IcedCoffeeScript await...defercannot block a synchronous cycle forEach.

Remember that IcedCoffeeScript compiles into JavaScript that does not support locking. After you called forEachin the array, you iterated through the entire array before any events could occur.

The good news is that you can get the behavior you want using the IcedCoffeeScript custom loop constructs. In your case

for info, index in anArray ->
  ...

JavaScript Async JavaScript.

+4

All Articles