2017-05-25 1 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'のような約束を - 約束は、新しいURLを作成するためのロジック設計 –

答えて

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

毎回により、非同期であり、クエリは非常に異なっています。それらすべてのプロセスに関数を使用することはできません。 – DragonKnight

+1

また '$ scope.whatIFinallyWant'は' response4'ではなく約束です –

関連する問題