await…defer 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'

Problem courtesy of: Charles


Your intuition is incorrect: IcedCoffeeScript’s await...defer
cannot block a synchronous forEach

Remember that IcedCoffeeScript compiles to JavaScript, which does not support blocking. Once you’ve called forEach
on an array, you’ve committed to iterating through that entire array before any events can fire.

The good news is that you can get the behavior you want by using IcedCoffeeScript’s own loop constructs. In your case,

for info, index in anArray ->

For more information on dealing with JavaScript’s non-blocking event model, check out my new book,
Async JavaScript


Solution courtesy of: Trevor Burnham

稿源:Node.js Recipes (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » await…defer in forEach loop

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录