0

I want multiple methods to get loaded completely before I proceed in my web application. For that I have done following -

      function getData(){
        var defer = $q.defer();
        $http.get("/echo/json/").success(function(data, status) {
            getData2();
            getData3();
            $timeout(function(){        
                 defer.resolve(data);
            }, 1000); 
        });
        return defer.promise;
      }

here, getData2() and getData3() will also do ajax calls. So I have to wait these methods to complete there call and then I have to return promise of main method.

This is working good , but giving me performance issue. Any other way I can do this?

2 Answers 2

5

If order is not important use $q.all() as follow:

$q.all([getData1(), getData2(), getData3()])
    .then(function(result){
        // result[0] is output of getData1() 
        // result[1] is output of getData2()
        // result[2] is output of getData3()
    });

But if order is important, call them in chain as follow:

getData1()
    .then(function(result1){
         return getData2();
    })
    .then(function(result2){
         return getData3();
    })        
   .then(function(result3){
         // your other codes
    });
Sign up to request clarification or add additional context in comments.

Comments

1

Assuming that all getDataX functions return promises, you should chain them like so:

getData()
.then(function(result){
  return getData1();
})
.then(function(result1){
  return getData2();
})...

Comments

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.