等待回调结束以在 Angular 中继续执行
Wait until a callback ends to continue execution in Angular
我在理解回调的工作原理时遇到了一些问题。
我正在编写一个必须验证用户输入的函数。
在函数内部,我必须对 API 进行 HTTP GET 调用以根据用户输入执行检查。
问题是验证函数是从流程函数调用的,提交函数是在我在 validate() 中进行的 HTTP 调用之前调用的。
我无法编辑流程功能,因为它是其他组件使用的功能。
form.process = function(){
// do stuffs
validate();
submit();
}
form.validate = function () {
// lots of checks regarding the model
...
// HTTP GET call
}
是否可以让提交函数等到 validate() 中的 HTTP GET 调用结束?
提前致谢:)
您必须将验证修改为 return 这样的承诺:
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;
}
现在你可以像这样在过程函数中做任何你想做的事情:
form.process = function(){
// do stuffs
validate().then(function(response){
submit();
}, function(reject){
// do something like showing error.
});
}
如果你有更多的组件使用这个功能,你必须全部这样编辑。
无论如何,这是在组件的每个 "validate" 函数中实现其他 GET 调用的最佳方式。
我在理解回调的工作原理时遇到了一些问题。 我正在编写一个必须验证用户输入的函数。 在函数内部,我必须对 API 进行 HTTP GET 调用以根据用户输入执行检查。
问题是验证函数是从流程函数调用的,提交函数是在我在 validate() 中进行的 HTTP 调用之前调用的。 我无法编辑流程功能,因为它是其他组件使用的功能。
form.process = function(){
// do stuffs
validate();
submit();
}
form.validate = function () {
// lots of checks regarding the model
...
// HTTP GET call
}
是否可以让提交函数等到 validate() 中的 HTTP GET 调用结束?
提前致谢:)
您必须将验证修改为 return 这样的承诺:
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;
}
现在你可以像这样在过程函数中做任何你想做的事情:
form.process = function(){
// do stuffs
validate().then(function(response){
submit();
}, function(reject){
// do something like showing error.
});
}
如果你有更多的组件使用这个功能,你必须全部这样编辑。 无论如何,这是在组件的每个 "validate" 函数中实现其他 GET 调用的最佳方式。