2015-02-12 60 views
3

後,這是我在控制器代碼採用了棱角分明怎樣才能撥打電話完成一堆異步調用

myFactory.getPoints().success(function (data) { 
    $scope.points = data; 
}); 

myFactory.getStates().success(function (data) { 
    $scope.states = data; 
}); 

myFactory.getLeases().success(function (data) { 
    $scope.leases = data; 
}); 

我期待$ scope.leases後$ scope.points和$ scope.states得到值獲得他們的價值。我知道$ q與.then不同步。是對的嗎?

答:我從答案推導如下

$q.all([ 
     myFactory.getPoints().success(function (data) { 
      $scope.Points = data; 
     }).error(function (data) { 
      $scope.error = "An Error has occurred while loading Points! " + data.ExceptionMessage; 
     }), //more, more, more 

    ]).then(function() { 
     myFactory.getLease().success(function (data) { 
      $scope.leases = data; 
     }).error(function (data) { 
      $scope.error = "An Error has occurred while loading Leases! " + data.ExceptionMessage; 
     }) 
}); 

回答

2

問題是成功()不返回原始承諾then()調用返回一個承諾(使用從回調函數返回的值解析),而.success()是更傳統的註冊回調方式,並且不返回承諾。

所以,妥善的解決辦法是

$q.all([ 
    myFactory.getPoints().then(function (response) { 
     $scope.points = response.data; 
     return response.data; 
    }), 

    myFactory.getStates().then(function (response) { 
     $scope.states = response.data; 
     return response.data; 
    }), 

    myFactory.getLeases().then(function (response) { 
     $scope.leases = response.data; 
     return response.data; 
    }) 
]).then(function(responses) { 
    // xxx 
}); 
4

您可以鏈的承諾一起,以讓他們同步執行:

myFactory.getPoints().success(function (data) { 
    $scope.points = data; 

    return myFactory.getStates(); 
}) 
.success(function (data) { 
    $scope.states = data; 

    return myFactory.getLeases(); 
}) 
.success(function (data) { 
    $scope.leases = data; 
}); 
+0

不一定三個承諾。我有5個可以異步調用的承諾,第6個調用應該在所有其他5個調用完成之後。 – Venu 2015-02-12 05:43:39

+0

@Venu檢查我的答案,你可以得到一個想法如何鏈接一個承諾後五個其他職能。 – Rebornix 2015-02-12 05:45:25