处理Angularjs的承诺

时间:2014-09-23 16:27:03

标签: angularjs

我想知道在有条件的情况下如何正确处理承诺。

例如我有这段代码:

if(something == true) {
  loginObj.$login("anonymous").then(function(){ //handling the promise
    //do something with the promise
    //do something line 1
    //do something line 2
    //do something line 3
    //do something line 4
    //do something line 5
  });
}
else {
  //do the same thing line 1
  //do the same thing line 2
  //do the same thing line 3
  //do the same thing line 4
  //do the same thing line 5
}

我希望你能看到我的问题。如果something为真,那么在执行我的代码行之前,我将不得不等待承诺解决。但是,我的else块几乎包含所有相同的代码行,但我不得不重复自己。

为什么我可以避免这种重复?

4 个答案:

答案 0 :(得分:1)

放下一个要调用的函数?

$scope.doTheSame= function()
{

}

if(something == true) {
  loginObj.$login("anonymous").then(function(){ //handling the promise
    //do something with the promise
    $scope.doTheSame()
  });
}
else {
  $scope.doTheSame()
}

并传递所需的参数,或者如果您正在使用范围对象,您仍然可以访问它们

答案 1 :(得分:1)

在'finally / always'块中执行重复的行。

例如,如果使用$ q,

var outputPromise = getInputPromise()
.fin(function () {
    // close files, database connections, stop servers, conclude tests
});

或者如果使用Jquery ......

$.get( "test.php" ).always(function() {
  alert( "$.get completed with success or error callback arguments" );
});

或者,如果您的代码不能构造为使得登录备用方法可以在promise链中流动,那么您可以简单地将两个登录函数移除到单个函数,该函数返回一个promise然后链接该函数,如下所示。

http://plnkr.co/edit/nJRaBb04JpLdHicgxg2u?p=preview

<!DOCTYPE html>
<html>

  <head>
    <script data-require="jquery@*" data-semver="2.1.1" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <h1>Hello Plunker!</h1>
    <button id="loginBtn">Login</button>

    <script>

    function login1(){
       var $def =$.Deferred();
       window.setTimeout(function(){
         $def.resolve("loginMethod1");
       },1000);
       return $def.promise();
    }

    function login2(){
       var $def =$.Deferred();
       window.setTimeout(function(){
         $def.resolve("loginMethod2");
       },1000);
       return $def.promise();
    }

    function login(val){
      var $def =$.Deferred();
      if(val){
        login1().then(function(res){
           $def.resolve(res);
        });
      }
      else{
        login2().then(function(res){
           $def.resolve(res);
        });
      }
      return $def.promise();
    }

    $("#loginBtn").bind("click",function(){
        login(Math.random()>0.5)
        .then(function(res){
          console.log(res + " ...do everythign else here");
        });
    });

    </script>
  </body>

</html>

答案 2 :(得分:1)

if(something == true) {
  loginObj.$login("anonymous").then(function(){ //handling the promise
    //do something with the promise
    doSomething();
  }).
  catch(function() { // catch code } ).
  finally(function() { // finally code });
}
else {
  doSomething()
}

function doSomething() {
  //do the same thing line 1
  //do the same thing line 2
  //do the same thing line 3
  //do the same thing line 4
  //do the same thing line 5
}

答案 3 :(得分:0)

我喜欢使用$ q.when()/ $ q.reject()在这样的情况下创建已解决的承诺。

var promise;
if ( something === true ) {
    promise = loginObj.$login("anonymous")
    .then(
        function(){ //handling the promise
            //do something with the promise
        }
     );
}
else {
    promise = $q.when("somethingelse");
    //promise = $q.reject("somereason");
}
promise.then(
    function (somethingelse) {
        //do something line 1
        //do something line 2
        //do something line 3
        //do something line 4
        //do something line 5
    }
);
相关问题