简体   繁体   English

等待承诺?

[英]Waiting for a promise?

I have the following angularjs code: 我有以下angularjs代码:

$scope.clients = commonFactory.getData(clientFactory.getClients());
if ($scope.clients.length > 0) {
    $scope.sampleForm.ClientId = $scope.clients[0].ClientId;
}

And the getData function in commonFactory: 而commonFactory中的getData函数:

factory.getData = function (method) {
    method.then(function (response) {
        return response.data;
    }, function (error) {
        $rootScope.alerts.push({ type: 'error', msg: error.data.ExceptionMessage });
    });
};

The problem is that $scope.clients.length is undefined when it hits that line because of the async call. 问题是,由于异步调用,$ scope.clients.length在遇到该行时未定义。

Is there a way to not do my length check until I know that $scope.clients has been assigned? 有没有办法不进行长度检查,直到我知道已经分配了$ scope.clients? I've looked at something like this: 我看过这样的事情:

$scope.clients = commonFactory.getData(clientFactory.getClients()).then(function () {
    if ($scope.clients.length > 0) {
        $scope.sampleForm.ClientId = $scope.clients[0].ClientId;
    }
});

Trying to chain my then promises, but no dice... the goal here is to have the getData method to avoid a bunch of boilerplate code for catching errors... maybe I'm going about this wrong? 试图链我then承诺,但没有骰子......这里的目标是让GetData方法,以避免一堆烦人的代码捕获错误...也许我要对此错了吗?

This is the most basic situation that promises are for. 这是承诺的最基本情况。 You simply need to make a promise with var deferred = $q.defer() when beginning an async operation, resolve the promise with deferred.resolve(result) when the async operation is complete, and return deferred.promise in your function. 您只需要在开始异步操作时使用var deferred = $q.defer()进行承诺,在异步操作完成时使用deferred.resolve(result)解析promise,并在函数中返回deferred.promise Angular's asynchronous methods do this internally and return promises already, so you can just return those same promises rather than creating new promises with $q.defer() . Angular的异步方法在内部执行此操作并返回promises,因此您可以返回相同的promise,而不是使用$q.defer()创建新的promise。 You can attach a .then to anything that returns a promise. 您可以将.then附加到返回承诺的任何内容。 Further, if you return a value from a then function, that value will be wrapped in a promise so that the then chain can continue 此外,如果从then函数返回一个值,该值将包含在一个promise中,以便then链可以继续

angular.module('myApp', [])

.factory('myService', function($q, $timeout, $http) {
  return {
    myMethod: function() {
      // return the same promise that $http.get returns
      return $http.get('some/url');
    }
  };
})

.controller('myCtrl', function($scope, myService) {
  myService.myMethod().then(function(resp) {
    $scope.result = resp.data;
  });
})

And here is a bit more fun with the chaining: 链接更加有趣:

.factory('myService', function($q, $timeout, $http) {
  return {
    myMethod: function() {
      // return the same promise that $http.get returns
      return $http.get('some/url').then(function() {
        return 'abc';
      });
    }
  };
})

.controller('myCtrl', function($scope, myService) {
  myService.myMethod().then(function(result) {
    console.log(result); // 'abc'
    return someOtherAsyncFunc(); // for example, say this returns '123'
  }).then(function(result) {
    console.log(result); // '123'
  });
})

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

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