1

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?

3
  • I'm not really sure what you're asking. Is it that $scope.userName = data; never happens? If so, I would set a break point on that line to see if it ever gets hit, and what the value of data is. Commented Dec 7, 2018 at 15:58
  • It goes inside the loop but then goes to the next line of code without updating the userName as it still waiting for the promise to resolve. So when I actually use the userName I get the old value instead of newer one returned from the promise. Commented Dec 7, 2018 at 17:10
  • Just move myService.save() code block inside of the .then(), just below $scope.userName = data; line Commented Dec 7, 2018 at 21:33

2 Answers 2

1

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) {
  });
});
Sign up to request clarification or add additional context in comments.

2 Comments

Will try this and let you know.
Good, to more information you can see this link
1

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  

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.