Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for a function to execute before proceeding in code block?

I have a function $scope.save(). Here am calling another function $scope.validateFormat()just to validate some value Inside validate function am making one Api call and checking the result if value is valid am returning and allowing the save to save my value. If invalid am setting the value setvalidity as false and throwing error. My doubt here is when i tried to call validateFormat() before completing this function save function is getting complete.

      $scope.save() = function(){
        // some code
        $scope.validateFormat();// calling the validate function
       // codde for saving value

       }
      $scope.validateFormat(){
      // some API to get result
      if(success){
      // some code
       }
     else{
      $scope.filestatus.editFileField.$setValidity("fileField", false);
       return false;
        }

}

like image 898
JOGO Avatar asked Feb 27 '26 20:02

JOGO


1 Answers

As I mentioned in the comment, here's an example using callbacks:

$scope.save = function(){
    // some code
    $scope.validateFormat(function (data) {
        if(!data.err) {
            // code for saving value
        }
    });
}

$scope.validateFormat = function(callback){
    // some API to get result
    $http.get('/something').then(function (success, error) {
        if(success){
            // some code
            callback({err: false});
        }
        else{
            $scope.filestatus.editFileField.$setValidity('fileField', false);
            callback({err: true});
        }
   });
}

You should adapt this according to your needs.

For more info regarding callbacks in javascript take a look at this answer.

like image 178
pgrodrigues Avatar answered Mar 02 '26 08:03

pgrodrigues



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!