AngularJS如何等待承诺返回

时间:2017-02-23 07:07:31

标签: angularjs

我的AngularJS应用程序具有这样的功能。

function createDefaultRequest() {
  
  var paramServiceId = currentUser.serviceId;
  var paramStatuses = myRequestService.getStatuses();      

  var paramSubServices = [];      
  paramSubServices = getSubService(paramServiceId);
  vm.subServices = paramSubServices;

  var defaultRequest = myRequestService.createRequest(
    paramServiceId, paramSubServices, paramStatuses);

  return defaultRequest;
}

function getSubService(paramServiceId) {
  medicalServiceFactory.subservices().query({
      serviceId: paramServiceId
    },
    function(subServicesData) {

      subServicesData.forEach(function(thisSubservice) {
        thisSubservice.ticked = true;
      });
      return subServicesData;
    },
    function(response) {
      vm.errorMessage = response.statusText;
    });
}

我希望myRequestService.createRequest(...)等到getSubService()返回。目前,paramSubServicesvm.subServices始终为空[]。如何在不移动createRequest(...)的回调块中的.query()的情况下实现此目的?感谢。

2 个答案:

答案 0 :(得分:0)

如果您的服务返回承诺,您可以等待承诺只是关键字.then()

myService.myFunction().then(function(result) {
    // Success callback      
}).then(function(reason) {
    // Error callback
});

来自$q docs

  

<强> then(successCallback, [errorCallback], [notifyCallback])

     

无论何时已经或将要解决或拒绝承诺,请致电   一个成功或错误回调一次异步   结果可用。使用单个参数调用回调:   结果或拒绝原因。另外,通知回调可以   被称为零次或多次以提供进度指示   承诺得到解决或拒绝。

答案 1 :(得分:0)

您可以使用$q依赖项,您可以在其中自定义异步请求。 您应该查看documentation或下面的代码段。

console.clear();
var _app = angular.module("ServiceModule", []);

_app.service("RequestSubService", ['$q', '$timeout', function ($q, $timeout) {
	this.getSubService = function(pServiceId) {
  	var deferred = $q.defer();
    
    //Timeout just to simulate the time it could take (e.g. 5sec)
    $timeout(function() {
    	if(pServiceId > 0)
      	deferred.resolve({status: 'success', serviceId: pServiceId})
      else
      	deferred.reject({status: 'error', serviceId: pServiceId});
    }, 5000);
    
    return deferred.promise;
  };
}]);

_app.service("RequestService", ['$q', '$timeout', function($q, $timeout) {
	this.createRequest = function(pServiceId) {
    return "Created request with serviceId: " + pServiceId;
  }
}])

_app.controller("ServiceCtrl", ['$scope', '$timeout', 'RequestSubService', 'RequestService', function($scope, $timeout, requestSubService, requestService) {
  $scope.serviceId = 1;
  
  $scope.fetchServices = function() {
  	$scope.message = "Fetching ...";
  	var promise = requestSubService.getSubService($scope.serviceId);
    promise.then(
      //Success
      function(data) {
        if(data.status === 'success')
          $scope.message = requestService.createRequest(data.serviceId);
      },

      //Error
      function(error) {
        $scope.message = "An error occured. ServiceId: " + error.serviceId;
      }
    );
  }
  $scope.fetchServices();
}]);
body {
  font-family: Arial, Sans-Serif;
}

span {
  display: block;
  font-style: italic;
  color: blue;
  margin: 20px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<div ng-app="ServiceModule">
  <div ng-controller="ServiceCtrl">
    <span>Input value > 0 will result in success. If value equals 0 it'll throw an error.</span>
    <input type="number" ng-model="serviceId" ng-change="fetchServices()"/>
    <span>{{message}}</span>
  </div>
</div>