简体   繁体   中英

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?

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 

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) {
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM