等待承诺?

Nic*_*ros 31 javascript promise angularjs

我有以下angularjs代码:

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

而commonFactory中的getData函数:

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

问题是,由于异步调用,$ scope.clients.length在遇到该行时未定义.

有没有办法不进行长度检查,直到我知道已经分配了$ scope.clients?我看过这样的事情:

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

试图链我的then承诺,但没有骰子......这里的目标是让GetData方法,以避免一堆烦人的代码捕获错误...也许我要对此错了吗?

m59*_*m59 34

这是承诺的最基本情况.您只需要var deferred = $q.defer()在开始异步操作时做出承诺,在deferred.resolve(result)异步操作完成时解析承诺,并deferred.promise在函数中返回.Angular的异步方法在内部执行此操作并且已经返回promise,因此您可以返回相同的promise而不是创建新的promise $q.defer().您可以附加一个.then返回承诺的任何内容.此外,如果从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;
  });
})
Run Code Online (Sandbox Code Playgroud)

链接更加有趣:

.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'
  });
})
Run Code Online (Sandbox Code Playgroud)