Question

Just to have a confirmation.

Suppose this Javascript code using AngularJs:

            $rootScope.myNeededBoolean = false;

            $rootScope.$on('userHasJustBeenAuthenticated', function(){
                if(!$rootScope.myNeededBoolean) {
                    $rootScope.myNeededBoolean = true; 
                    //determinant assignment to myNeededBoolean so that the following
                    //piece of code will be executed once and only once.
                    pieceOfCodeToExecuteOnlyOnce();
                }
            });

It is used to trigger a piece of code when the user is logged.

Suppose this code is triggered by two distinct codes simultaneously (using $rootScope.$broadcast for instance), focused on the same event: userHasJustBeenAuthenticated.

Javascript being mono-threaded AFAIK, can I assert that $rootScope.$on will be accessed twice SEQUENTIALLY in 100% of cases?

Indeed, I want the $rootScope.myNeededBoolean to be determinant so that pieceOfCodeToExecuteOnlyOnce is executed just once.

Was it helpful?

Solution

Javascript by default does not have thread. So the code block

 if(!$rootScope.myNeededBoolean) {
    $rootScope.myNeededBoolean = true; 
    //will execute only once
 }

will complete its execution before moving away.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top