如何等待回调函数的返回
How to wait the return of a Callback function?
如何正确实现该用例:在客户确认操作后,我想显示一个等待屏幕,直到回调功能完全执行。。。
我已经完成了以下操作,但REST调用是在调用srv.hideLoadingScreen()
之后执行的…://
对话服务:
srv.onApprove = function(callback){
srv.displayLoadingScreen();
callback();
srv.hideLoadingScreen();
};
控制器:
ctrl.showConfirmModal = function(){
//...
if(approved){
DialogService.onApprove(function(){
ctrl.performAction();
});
}
};
ctrl.performAction = function(){
console.log('performAction');
if(angular.isDefined(ctrl.selectedNumberList)){
var numberList = {
nbList: ctrl.selectedNumberList
};
MyService.launch(numberList, function(response){ // REST call
console.log('call ok');
}, function(error){
console.log('error');
});
}
};
更新:目前,我选择的解决方案避免了回调的回叫:关闭
ctr.perfomAction()
中的等待面板
MyService.launch(numberList, function(response){ // REST call
console.log('call ok');
DialogService.hideLoadingScreen();
}, function(error){
console.log('error');
DialogService.hideLoadingScreen();
});
您可以使用$http
服务返回Promise。
异步操作只有在完成并且调用堆栈清除后才会返回。由于我们将在它们被返回之前离开范围,所以您可以使用Promise来确保您获得值。
app.service('MyService', function($http) {
this.launch = function launch() {
return $http({ method: 'GET', url: '/endpoint' });
};
}
app.controller('MyCtrl', function(MyService) {
MyService.launch()
.then(function(response) {
});
});
$q
服务也可以为任何类型的异步调用返回promise。
使用Angular繁忙。这种方式应该适用于您:
应用
bower install angular-busy --save
- 将dist/angular-buss.js和dist/angular-buss.css添加到您的
index.html
- 添加
cgBusy
作为模块依赖项 angular.module('your_app', ['cgBusy']);
控制器
$scope.myPromise = MyService.launch(numberList, function(response){ // REST call...
部分
<div cg-busy="{promise:myPromise,
message:'Loading',
backdrop:false,
templateUrl:'myAwesomeTemplate.html',
delay:300,
minDuration:700} ">
</div>
编辑您的评论:
像这样的东西怎么样?
MyService.launch(numberList, function(response){
-----> $scope.myPromise = console.log('call ok'); <--------
}, function(error){
console.log('error');
});
相关文章:
- JavaScript回调函数
- 如何在回调函数中执行流
- 回调函数中传递参数的困难(Google Map API Markers)
- 如何正确地将参数传递给RequireJS回调函数
- 回调函数在python代码中离线
- 从AJAX回调函数中分离数据
- 赋值后的回调函数
- 如何在javascript回调函数中返回多个变量
- 函数表达式,返回回调函数
- 等待回调函数执行
- JavaScript回调函数和Google Feed API
- 如何从ajax成功回调函数中读取javascript变量
- 正在保存JavaScript内部回调函数中的值
- 有没有什么方法可以停止Jquery中的animate(也可以停止完整的回调函数)
- 如何在javascript中添加带有回调函数的按钮点击事件作为window.conf
- 在Golang回调函数中启用CORS
- 在初始函数完成之前调用回调函数
- jQuery Mobile:如何在$.Mobile.changePage之前运行回调函数
- 即使使用回调函数也无法返回值
- 为什么prototypjs观察到回调函数有绑定