如何等待回调函数的返回

How to wait the return of a Callback function?

本文关键字:回调 函数 返回 等待 何等待      更新时间:2023-09-26

如何正确实现该用例:在客户确认操作后,我想显示一个等待屏幕,直到回调功能完全执行。。。

我已经完成了以下操作,但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繁忙。这种方式应该适用于您:

应用

  1. bower install angular-busy --save
  2. 将dist/angular-buss.js和dist/angular-buss.css添加到您的index.html
  3. 添加cgBusy作为模块依赖项
  4. 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');
        });