My problem is pretty simple and I think lot of programmers already must have faced this. I am using angularjs and my javascript looks as follow:
controller('myController', function())
{
if(validateForm())
{
//do after-validation stuff
}
validateForm = function()
{
var val = undefined;
$http.get('api/validate/').
success(function(data){
val = true;
}).
error(function(data){
val =false;
});
while(!val)
{ // loop over till val has value
}
return val;
}
}
I have two questions:
1) when I make http call it returns a promise object and it resolves to either success or error function. If that is the case then the while loop in this code should not be infinite, but it is. By debugging I found that if I assign a value to variable 'var' then only the http call is made i.e when the loops ends. why http call, being a deferred call, waits on the while loop to finish?
2) If I remove the while loop, no matter what the value of 'var' is, the function returns. How can I make it return only if 'var' is defined?