2 个承诺一起返回 null



im 发出 2 个请求,但是当我在承诺之外调用变量时,它就会从结果中获取值,它会变为 null,但由于我依赖于 2 个不同承诺的最需要结果,并且我需要根据每个承诺的结果执行一个函数,我不知道如何解决它。

我的代码控制器:

$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);

尝试如下:

$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(( 上仍然是空的/未定义的,很容易理解为什么 console.logs 是未定义的。

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

您不能假设distanceTotal是在.then()函数之外定义的。唯一保证要定义的地方是在then()

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

我们需要做的就是创建一系列承诺。有了$q.all,我们可以在一个.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);
  ...
});