2

There are many stackoverflow questions related to (a)synchronous executions and promises, but I did not quite find an answer to this.

Imagine I have the following:

var number = 0;
someAsyncFunctionWithCallback(function(){
    number++;
});
// ^ execute the above multiple times

As the execution times of each call of the function varies, the callbacks will be called at different times. Therefore, I am wondering what the behavior of the variable-incrementing line will be. In Java, I can declare variables as synchronous such that every increment will be taken into account. With the code above, is each increment of the number guaranteed, or not necessarily?

3
  • i see no reason why each execution should not increment it, the question is at which point you want to test it and if you want to keep it just ++ increment or actual things that need to be chained or ordered Commented Dec 15, 2018 at 20:11
  • Per my experience on this, you should have no worries. I have not experienced a problem Commented Dec 15, 2018 at 20:12
  • @johnSmith I was worried that there might have been some kind of race condition, but an answer below said that javascript doesn't do real multi threading and therefore all variable access stays synchronous. Commented Dec 15, 2018 at 20:34

3 Answers 3

1

JavaScript is always synchronous with itself. This is not true multi-threading, which JS does not support or use.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, that makes sense. I wasn't completely sure about that.
1

As long as you can be sure of when and how often someAsyncFunctionWithCallback will run, there are no issues with this method. You only have to be aware of the fact that checking your variable at any given point will only reflect its current value based on how many times the callback has executed.

Comments

1

Each callback function(){ number++;} will be called later in non-deterministic order to increase number. Only one thing can be assured here is N callback execution will increase N times the variable number

1 Comment

Great to know. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.