2017-05-25 48 views
1

什麼是一個乾淨的方式來編寫這樣的代碼?多次,我必須使用先前請求的響應來從不同的來源和表格構建新的URL和彈性搜索查詢。如何在angular.js中編寫更好的順序承諾調用?

$scope.whatIFinallyWant = {}; 
$http.get(url1).then(function(response1){ 
    // creating new url2 & query with response1 
    $http.get(url2).then(function(response2){ 
     // creating new url3 & query with response2 
     $http.get(url3).then(function(response3){ 
      // creating new url4 & query with response3 
      $http.get(url4).then(function(response4){ 
       // using the final response in UI ... 
       $scope.whatIFinallyWant = response4; 
      }) 
     }) 
    }) 
}) 
+0

'同步promise' - 承諾是由設計 –

回答

2

鏈的承諾,像這樣

$scope.whatIFinallyWant = {}; 
$http.get(url1) 
.then(function(response1) { 
    // creating new url2 & query with response1 
    return $http.get(url2); 
}).then(function(response2) { 
    // creating new url3 & query with response2 
    return $http.get(url3); 
}).then(function(response3) { 
    // creating new url4 & query with response3 
    return $http.get(url4); 
}).then(function(response4){ 
    // using the final response in UI ... 
    $scope.whatIFinallyWant = response4; 
}); 
+0

很好的答案。謝謝, – DragonKnight

0

因爲$ http.get()返回解析數據(請結帳角文檔爲它的確切形狀:https://docs.angularjs.org/api/ng/service/ $ HTTP),您可以使用預定義的功能,形成URL,並調用$ http.get():

let makeUrl = (promiseResult) => { 
    let url 
    /* some logic */ 
    return $http.get(url); 
} 

let logErr = (err) => { 
    console.error("Whoops! " + err); 
} 

$http.get(url1) 
    .then(makeUrl) 
    .then(makeUrl) 
    .then(makeUrl) 
    .then((finalUrl) => { 
    $scope.whatIFinallyWant = finalUrl; 
    }) 
    .catch(logErr) 
+0

每次異步創建一個新的URL邏輯和查詢是非常不同的。不可能爲所有這些進程使用函數。 – DragonKnight

+1

也,'$ scope.whatIFinallyWant'將是一個承諾,而不是'response4' –