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 (b
Solution 1:
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.
Post a Comment for "Javascript: Weird Behavior In Foreach Loop"