如何访问返回的承诺的值?

时间:2017-05-24 19:55:45

标签: javascript asynchronous promise angular-promise

我确定我错过了一些关于同步性的明显和基本的东西,但是我无法理解它应该如何运作...

$scope.foo=[];

getFoo(url) {
  $scope.foo=$http.get(url).then(function (response) {
    var foo = [];
    //process response to get foo array. Console.log returns as expected here.
    return foo;
  });
}

这似乎只是将$scope.foo设置为promise对象。我错过了什么?如何在我的其余代码中实际使用promise的结果?

1 个答案:

答案 0 :(得分:4)

而不是return foo,您需要在回调中移动分配:

getFoo(url) {
  $http.get(url).then(function (response) {
    var foo = [];
    // process response to get foo array...
    $scope.foo = foo;
  });
}

使用promises时,return回调的值.then()只有在链接在一起时才能用于另一个.then()回调:

$http.get(url).then(function (response) {
  var foo = [];
  // process response to get foo array...
  return foo;
}).then(function (foo) {
  $scope.foo = foo;
});
相关问题