2017-03-27 62 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); 
    ... 
});