1
votes

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??

2
What do you mean with "precision"? Are you relying on the order in which total is built up which can cause precision issues, i.e, a + b + c or c + b + a?pimvdb
What is an "asynchronous forEach"?nnnnnn
@nnnnnn apologies. I had assumed Array.forEach to be async, but after reading some of the answers here. It doesn't seem to be!tommi
@pimvdb Hmm, let me try explaining here, I was concerned if there was a situation when there is c=a+b then at the same time, a f=a+c. Then the addition of either b or c might not be captured.tommi
No need to apologise. Not sure if you were fooled by the fact that forEach() takes a callback function as a parameter, but there are lots of synchronous functions that do that. If you're not using setTimeout(), setInterval() or an ajax function then chances are you're not dealing with asynchronous code. If you wrote your own async "loops" using setTimout() then you could theoretically have issues with more than one block of code updating the same variables (even though non web-worker JS executes on only one thread).nnnnnn

2 Answers

2
votes

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:

setTimeout(function() {doSomeStuff1For(10secs)},1)
setTimeout(function() {doSomeStuff2For(20secs)},1)

Those events will be executed like this (considering 10sec call got lucky to be first):

1 sec: doSomeStuff1
2 sec: doSomeStuff1
...
10 sec: ended doSomeStuff1
11 sec: started doSomeStuff2
...
30 sec: ended doSomeStuff2.
1
votes

I think count++ works the same as total += 10 so there will be no difference. But it does not matter anyway:. Javascript does not execute code parallel.

See also: http://ejohn.org/blog/web-workers/