Shrinivas
Shrinivas

Reputation: 853

How to achieve the required execution order in angularjs?

I have this piece of code:

angular.module('myApp').controller('appContoller', function($scope){

    var fun1 = function(){
        setTimeout(function() {console.log("aaaaa");}, 5000);
    }

    var fun2 = function(){
        console.log("bbbbb");
    }

    var myOrder = function(){
        fun1();
        fun2();
    }
});

Upon executing, the observed order is - first fun2, then fun1. How do I get them executed in the order fun1 first, then fun2?

Upvotes: 0

Views: 148

Answers (2)

Magus
Magus

Reputation: 15124

fun1 is doing a asynchronous job. So it let the code run and fun2 is executed. If you want to wait for fun1 end, you have multiple choices :

  • Use a callback as parameter of fun1

    var fun1 = function(callback) {
        setTimeout(function() {console.log("aaaaa"); callback()}, 5000);
    };
    
    var fun2 = function(){
        console.log("bbbbb");
    }
    
    var myOrder = function(){
        fun1(fun2);
    }
    
  • Use a promise

    angular.module('myApp').controller('appContoller', function($scope, $q){
    
        var fun1 = function(){
            var deferred = $q.defer();
    
            setTimeout(function() {console.log("aaaaa"); deferred.resolve()}, 5000);
    
            return deferred;
        }
    
        var fun2 = function(){
            console.log("bbbbb");
        }
    
        var myOrder = function(){
            fun1().then(fun2);
        }
    });
    

Upvotes: 1

rakesh
rakesh

Reputation: 71

Just remove the setTimeOut for 5 sec, that's the reason the order behind that. Still if you need the timeout function necessary then call function 2 inside timeout function.

Upvotes: 0

Related Questions