JavaScript: Weird behavior in forEach loop

My code looks like this:

someArray.forEach(x => {
// do something
console.log(‘calling api for ‘ + x);
callAnHttpApiAsync(...);
sleep(10);
});

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   

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.

Answers:

Answer

Full disclosure: I don't really know node.js, only client-side javascript, but I think the explanation works here as well.

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.