How to wait for a function to execute before proceeding in code block?
17,500
Solution 1
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.
Solution 2
I think you should create promises here using $q service.
$scope.validateFormat = function(callback){
var deferred = $q.defer();
// some API to get result
$http.get('/something').success(function(data){
deferred.resolve(data);
.error(function(err){
$scope.filestatus.editFileField.$setValidity('fileField', false);
deferred.reject(err)});
return deferred.promise();
}
Author by
JOGO
Updated on June 30, 2022Comments
-
JOGO almost 2 years
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; }
}
-
JOGO over 8 yearshere using callback dint solve this problem. Cos validateFormate() function am calling inside a specific condition within save function. $scope.save= function(){ if(fieldVal=="NO"){ validate(); } So i can't block the entire save code just for a specific case. any other thought? }