Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when there is code below a $location.path('new/path')?

Tags:

angularjs

If I execute a path change like $location.path('new/path'), what happens with the code below this path change? As I understand, a path change does not stop the rest of the code from running, but what is actually happening? Will the code finish up and only then the path will change? So if this code is very time consuming (say saving something to a server on a slow network connection), will the location change will be similarly late? Or will things happen in parallel?

like image 419
EricC Avatar asked Jun 21 '15 21:06

EricC


1 Answers

Here's a small test, it looks like it finishes running the code, then changes the location. Have a look at the console in the jsfiddle, you'll see both loops going, but one after the other.

As @SilverlightFox points out, there is no parallel processing in javascript.

//this one loads first, executes the loop, then changes location. 
function HomeCtrl($scope, $location) {
    $location.path('/about');
    var i  = 0;
    while(i < 1000000000) {
        if(i % 100000000 === 0) {
            console.log('home')   
        }
       i++;
    }
}

//this loop executes second. 
function AboutCtrl($scope) {
    $scope.name = 'John';
     var i  = 0;
    while(i < 1000000000) {
        if(i % 100000000 === 0) {
            console.log('about')   
        }
        i++
    }
}

If the code in HomeCtrl is changed to include a timeout, the location changes first because the timeout breaks the flow of the program and schedules the timeout to execute after the AboutCtrl executes.

//changes location first, executes AboutCtrl, then does the "home" loop
function HomeCtrl($scope, $location) {
    $location.path('/about');
    setTimeout(function() {
        var i  = 0;
        while(i < 1000000000) {
            if(i % 100000000 === 0) {
                console.log('home')   
            }
           i++;
        }        
    }, 1)
}

With a proper async request it's the same as the timeout: location changes, 'about' loop runs, then the http request finishes. So, an ajax call to update databases on a slow connection does not stop the application from changing routes.

//changes location, executes 'AboutCtrl', then finishes the http request and 
//executes the 'home' loop.
function HomeCtrl($scope, $location, $http) {
    $location.path('/about');
    $http.get('/echo/json/').success(function() {
        var i  = 0;
        while(i < 1000000000) {
            if(i % 100000000 === 0) {
                console.log('home')   
            }
           i++;
        }        
    });

If I was changing route because of a network call, I would do it in the succes/error promise or callback, if that was the intention.

like image 194
Jorg Avatar answered Nov 15 '22 06:11

Jorg