await…defer in forEach loop

综合技术 Node.js Recipes (源链)

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


The iteration of the return table I've got the following component where I pull in some JSON and I'm trying to get some nested information with {} , however I...
Makefile – 失落的艺术 译者吐槽:尽管 Makefile 似乎与前端渐行渐远,不过还是有很多神奇海螺一般的魔法值得我们去入门,本文与前端的内容相结合进行了一番介绍和示例科普,适合所有对 Makefile 一脸懵逼的小伙伴。 原文: http://www. o...
Clojure 风格的 JavaScript 并发编程 在看到第一行JavaScript代码之前,我要啰嗦一下为什么要用 clojure core.async 的异步风格。 TL;DR SLIDES Communicating Sequential Processes 通信顺序进程, 是计算机科学中用于一种描述并发系统中交...
Serving a client side a component for my node modu... I'm building a NodeJS game engine. When the user creates an instance of the engine they must pass it an existing http server. The engine then attaches...
Looking back at 2017 Hey friends! This is the time of the year where I look back at these last 12 months. With emojis, as per us’! It’s a bit long so feel free to skip to ...
Node.js Recipes责编内容来自:Node.js Recipes (源链) | 更多关于

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

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

使用声明 | 英豪名录