在AngularJS中使用Promise进行$ http-calls的条件链接

Jul*_*ost 4 javascript angularjs angular-promise

我必须顺序执行三个不同的$ http-calls,它们相互依赖.到目前为止,我的工作解决方案是这样的

$http.get(".../1/...").success(function(){
    $http.get(".../2/...").success(function(){
        $http.get(".../3/...").success(function(){

        });
    });
});
Run Code Online (Sandbox Code Playgroud)

现在有一些变化:如果条件为真,则应跳过第一个调用.我可以这样做:

if(skipCallOne) {
    $http.get(".../2/...").success(function(){
        $http.get(".../3/...").success(function(){

        });
    });
} else {
    $http.get(".../1/...").success(function(){
        $http.get(".../2/...").success(function(){
            $http.get(".../3/...").success(function(){

            });
        });
    });
}
Run Code Online (Sandbox Code Playgroud)

这显然会导致大量的代码复制.我看到如果我使用特定$ http-calls的propper函数,这可以减少.但据我所知,更好的解决方案是正确使用和链接$ http-promises,如下所示:

$http.get(".../1/...").then(function(){
    return $http.get(".../2/...");
}).then(function() {
    return $http.get(".../3/...");
}).then(function() {

});
Run Code Online (Sandbox Code Playgroud)

但现在我的问题是,我如何以最少的代码复制条件跳过第一次调用?

Phi*_*hev 10

你可以尝试这种方法:

$q.when(skipCallOne || $http.get(".../1/..."))
  .then(function() {
    return $http.get(".../2/...");
  }).then(function() {
    return $http.get(".../3/...");
  }).then(function() {
});
Run Code Online (Sandbox Code Playgroud)

  • 在这里完全同意你的观点。我编辑了我的答案。让我们看一下文档: .when(value) 将一个可能是值或(第 3 方)then-able 承诺的对象包装到 $q 承诺中。当您处理的对象可能是也可能不是承诺,或者承诺来自不可信的来源时,这非常有用。 (2认同)