2017-03-27 75 views
1

即时做出2个请求,但是当我从结果中得到的值,如果我调用变量之外的变量,它会得到空值,但因为我依赖2个不同的promisses最需要的结果,我也需要根据每个承诺的结果执行功能,我不知道如何解决它。2 promisses一起返回null

我的代码控制器:

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

回答

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

,或者如果你需要的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,很容易看出为什么console.logs未定义。

由于混乱的另一个编辑:

你不能假设distanceTotal.then()功能之外定义。它将被定义的唯一保证位置在then()之内。

+0

谢谢Fissio,你能告诉我我做错了什么或为什么没有工作? – Pedro

+0

你好,我做了一个console.log(distanceTotal)在承诺之外,没有任何显示,给了我一个未定义的“ – Pedro

+0

检查我的编辑;问题可能是一样的,你需要使用'distanceTotal'内的代码' 。然后()'。 – Fissio

0

由于这有多个承诺,你想同时使用这两个答复,我会解决这个问题,使用$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); 
    ... 
});