如何在 angular.js 中编写更好的顺序 promise 调用?

How to write better sequential promise calls in angular.js?

编写这样的代码的简洁方法是什么?我不得不多次使用先前请求的响应来构建新的 URL 和来自不同来源和表的弹性搜索查询。

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

由于 $http.get() returns 已解析数据(请查看 angular 文档以了解其确切形状: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)

像这样链接承诺

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