1

I'm having some problems understading how the callbacks work. I'm writing a function that has to validate the user's input. Inside the function I have to make an HTTP GET call to my API to perform a check based on the user input.

The problem is that the validate function is called from the process function and submit function is called before the HTTP call that I make inside validate(). I cannot edit process function because it is a function used by other components.

form.process = function(){
     // do stuffs
     validate();
     submit();
}

form.validate = function () {
    // lots of checks regarding the model
    ...
    // HTTP GET call
}

Is it possible to let the submit function waits until the HTTP GET call inside validate() ends?

Thanks in advance :)

Roberto Milani
  • 760
  • 4
  • 20
  • 40
  • does your `validate` function returns any `deferred` or `promise` ? – Ja9ad335h Aug 22 '16 at 14:18
  • 1
    If you cannot edit `process`, you're out of luck. HTTP requests are always asynchronous, so `submit()` will run before the HTTP request returns. (Well, apparently [you can make them synchronous](http://stackoverflow.com/questions/133310/how-can-i-get-jquery-to-perform-a-synchronous-rather-than-asynchronous-ajax-re) but it will make the browser hang.) – Thomas Aug 22 '16 at 14:19
  • I'm confused... why can't you edit the process function? It's calling the validate function, so even if other components are using the process function, it's still calling the validate function and if that doesn't work, then nor will it work when other components call it... – Ted Aug 22 '16 at 14:28
  • well it does not make sense :) your `process()` function is not working as you want it to, so you will have to change it – Jahongir Rahmonov Aug 22 '16 at 15:54

1 Answers1

3

You MUST modify validate to return a promise like this:

form.validate = function () {
    var deferred = $q.defer();
    // lots of checks regarding the model
    ...
    // In http GET call:
    // If success
    deferred.resolve(<any value>);
    // If errors
    deferred.reject(<any value>);
    // and now return the promise
    return deferred.promise;
}

Now you CAN do anything you want in process function like this:

form.process = function(){
   // do stuffs
   validate().then(function(response){
      submit();
   }, function(reject){
      // do something like showing error.
   });
}

If you have more components that use this function, you MUST edit all like this. Anyway, this is the best way to implement other GET calls in each "validate" function of your components.