简体   繁体   English

等待回调结束以继续在Angular中执行

[英]Wait until a callback ends to continue execution in Angular

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. 在函数内部,我必须对API进行HTTP GET调用,以根据用户输入执行检查。

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(). 问题在于,我从流程函数中调用了validate函数,而在validate()内部进行的HTTP调用之前,则调用了commit函数。 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? 是否可以让Submit函数等待validate()内的HTTP GET调用结束?

Thanks in advance :) 提前致谢 :)

You MUST modify validate to return a promise like this: 您必须修改validate以返回如下承诺:

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. 无论如何,这是在组件的每个“验证”功能中实现其他GET调用的最佳方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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