2个promisses一起返回null

时间:2017-03-27 12:21:57

标签: javascript angularjs angularjs-scope angular-promise

即时发出2个请求,但是当我从结果中获取值时,如果我在promise之外调用变量,它将获得null,但是因为我依赖于2个不同promisses的requrest结果而且我还需要执行一个基于on的函数每个承诺的结果我都不知道如何解决它。

我的代码控制器:

$scope.originLatLong = null;
    $scope.destinationLatLong = null;

    //Get LAT and LONG from origin and destionation http://something/{Code}
    $http.get('something/getLatLng/'+$scope.originAirport).then(function(response){
        $scope.originLatLong = response.data; //doesnt return null

    });

$http.get('something/'+$scope.destinationAirport).then(function(response){
        $scope.destinationLatLong = response.data; //doesnt return null

    });

console.log($scope.originLatLong) //returns null
console.log($scope.destinationLatLong) //returns null
var distanceTotal = calculate($scope.destinationLatLong,$scope.originLatLong);

2 个答案:

答案 0 :(得分:1)

试试这样:

$scope.originLatLong = null;
$scope.destinationLatLong = null;

$http.get('something/getLatLng/'+$scope.originAirport).then(function(response){
    $scope.originLatLong = response.data;
    return $http.get('something/'+$scope.destinationAirport)
})
.then(function(response) {
    $scope.destinationLatLong = response.data;
    var distanceTotal = calculate($scope.destinationLatLong,$scope.originLatLong);
})

或者如果你需要在.then()之外的distanceTotal,请在http调用之前声明它:

$scope.originLatLong = null;
$scope.destinationLatLong = null;
var distanceTotal;

$http.get('something/getLatLng/'+$scope.originAirport).then(function(response){
    $scope.originLatLong = response.data;
    return $http.get('something/'+$scope.destinationAirport)
})
.then(function(response) {
    $scope.destinationLatLong = response.data;
    distanceTotal = calculate($scope.destinationLatLong,$scope.originLatLong);
})

编辑并解释原始问题:

$http调用是异步的,这意味着浏览器发出请求,并且当浏览器等待服务器的响应时,后面的代码继续运行。这意味着在您的示例中执行代码的顺序类似于

$http call
The other $http call
console.log($scope.originLatLong)
console.log($scope.destinationLatLong)
var distanceTotal = calculate($scope.destinationLatLong,$scope.originLatLong);
$scope.originLatLong = response.data;
$scope.destinationLatLong = response.data;

在console.log()s中看到变量如何仍为null / undefined,很容易理解为什么console.logs未定义。

由于混淆而进行的另一次编辑:

您不能假定distanceTotal.then()函数之外定义。它将被定义的唯一保证位置是then()

答案 1 :(得分:0)

由于这有多个承诺,并且您希望同时使用这两个响应,我将使用$q.all来解决此问题。

我们需要做的就是创建一个承诺数组。使用$q.all,我们可以同时获得承诺和#39}。一个.then()的回复。以下是:

var promises = [];
promises.push($http.get('something/getLatLng/'+$scope.originAirport));
promises.push($http.get('something/'+$scope.destinationAirport));

$q.all(promises).then(function(response) {
  $scope.originLatLong = response[0].data;
  $scope.destinationLatLong = response[1].data;

  console.log($scope.originLatLong) 
  console.log($scope.destinationLatLong) 
  var distanceTotal = calculate($scope.destinationLatLong, $scope.originLatLong);
  ...
});