I’ve a asynchronous forEach looping through an array
var anArray = [.....values inside...];
anArray.forEach(function (s) {
...
});
And also a 2 global variables that will be updated:
var count = 0;
var total = 0;
During the foreach, I’ll be updating both variables. As the foreach is async, I might expect multiple iterations to be running at the same time. Which means that that my variables might be over written.
For count, it’s fine as all I’m doing is a count++ in each loop.
However for total, different values will be added during each look.
Is there anyway for me to ensure that total will be updated without any loss of precision??
There are no threads in Javascript. “Asynchronous” merely means that it will post the event into the queue and then evaluate it when the main thread is avialable. Therefore, you will never get any kind of synchronization issues in JS.
For example, if you run:
Those events will be executed like this (considering 10sec call got lucky to be first):