aman
aman

Reputation: 6242

Angularjs promise wait for result

In my angularjs app I have the following code on button click:

 if (!$scope.isChecked) {
    $scope.getExistingName($scope.userName).then(function (data) {  
        $scope.userName = data;    
    });
  }

  //some processing code here then another promise  

 myService.save($scope.userName,otherparams).then(function (res) {
       //route to page
    }, function (err) {
 });

The issue here is if $scope.isChecked is false, it goes inside the promise and since it takes time to resolve it comes out and goes to next line of code. Because of this $scope.userName is not updated and uses old values instead of the updated value returned.

Whats the best way to handle this?

Upvotes: 1

Views: 75

Answers (2)

Emiliano Cortez
Emiliano Cortez

Reputation: 76

You can use $q. First you have to inject $q in your angular controller.

 //Create empty promise
 var promise;

 if (!$scope.isChecked) {
   promise = $scope.getExistingName($scope.userName).then(function (data) {  
        $scope.userName = data;    
    });
  }

 // Wait or not for your promise result, depending if promise is undefined or not.
 $q.all([promise]).then(function () {

  //some processing code here then another promise  

  myService.save($scope.userName,otherparams).then(function (res) {
        //route to page
     }, function (err) {
  });
});

Upvotes: 1

Andrea Naspi
Andrea Naspi

Reputation: 119

If the myService.save need to wait for the $scope.getExistingName promise just compute that operation inside the "then" statement.

 if (!$scope.isChecked) {
    $scope.getExistingName($scope.userName).then(function (data) {  
         $scope.userName = data;    
         myService.save($scope.userName,otherparams).then(function (res) {
             //route to page
         }, function (err) {
         });
    });
  }

  //some processing code here then another promise  

Upvotes: 1

Related Questions