问题描述
我的代码如下所示:
someArray.forEach(x => {
// do something
console.log(‘calling api for ‘ + x);
callAnHttpApiAsync(...);
sleep(10);
});
http api调用是异步的(但我不使用任何await / async语法)和日志一旦api发回回复的东西。会发生什么是forEach循环完成后我才开始看到记录的响应。我期望在循环结束之前看到一些响应(我尝试增加睡眠量),但无论我等待多久或循环多长时间,循环结束后都会记录响应。我使用节点的睡眠库。我看到这样的事情:
The http api call is async (but I don’t use any await/async syntax) and logs something once the api sends back the response. What happens is that the forEach loop is completed and I start to see the logged responses ONLY AFTER that. I’d expect to see some responses before the loop is over (I tried increasing the amount of sleep), but no matter how long I wait or how long the loop is the responses are logged always after the loop is over. I use a sleep library of node. I see something like this:
calling api for 1
calling api for 2
calling api for 3
...
calling api for 10000
got response for 1
got response for 2
got response for 3
...
got response for 10000
我已经通过使用for-of和await / async解决了这个问题(请让我知道你是否有更好的想法),但我无法理解这种奇怪行为的原因。为什么我只在完整循环后得到响应?有任何想法吗?抱歉格式化,但我在移动设备上。
I solved already this issue by using for-of and await/async (please let me know if you have better ideas), but I can’t understand the reason of this weird behavior. Why do I get the responses only after the full loop? Any ideas? Sorry for the formatting but I’m on mobile.
推荐答案
完全披露:我真的不知道node.js,只是客户端javascript,但我认为这里的解释也适用。
Full disclosure: I don't really know node.js, only client-side javascript, but I think the explanation works here as well.
问题的症结在于异步并不意味着并行。当您调用异步操作时,它将被放入队列中。当JSVM完成执行当前正在运行的代码时(在这种情况下是包含 forEach
的代码),然后才会执行异步队列中的第一个操作并执行它;然后,当它完成时,它会在那之后运行,依此类推。即无论你开始多少次异步工作,一次只能运行一次。
The crux of the issue is that "asynchronous" doesn't mean "parallel". When you call an asynchronous operation, it gets placed in a queue. When the JSVM finishes executing the code it's currently running (which in this case is the code containing your forEach
), then and only then does it take the first operation in the async queue and execute it; then, when that finishes, it runs the one after that, and so on. I.e. no matter how many async jobs you start, only one will ever run at a time.
这篇关于JavaScript:forEach循环中的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!