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.
forEachis synchronous. IfcallAnApiAsyncisn't then it makes no difference if it in afororforEachloop.asynccalls to complete. If you wantasyncapi's to complete and then run the next loop, you need to use theforloop. github.com/babel/babel/issues/909.forEachall other tasks, let them be synchronous or asynchronous has to wait up until it finishes. So that's what simply happening here. Thesleepfunction as understand is synchrnous as mentioned in the NPM page These calls will block execution of all JavaScript by halting Node.js' event loop! so you are only slowing down your.forEach()and during that time nothing gets executed.