在按钮点击之前让承诺保持未解决状态

时间:2018-02-26 11:22:40

标签: javascript angularjs promise

我现在有这样的事情:

var promise = $interval(function(){
                        if(scope.state.showDialog === false){
                            console.log("Done");
                            $interval.cancel(promise);
                            return true;
                        } else {
                            console.log("Not canceled");
                        }
                    },200);
                    return promise;

我想要实现的是在按下按钮后解决间隔承诺,以便我可以进一步链接它。我试图建立一个可链接的对话框,但我认为我已经用这种方法将自己描绘成了一个角色,因为看起来我需要添加计数才能解决间隔。

那么,在点击一个按钮之前我怎么能保持承诺呢?我很难过。

1 个答案:

答案 0 :(得分:1)

return promise;永远不会被退回。

您无法返回value之外的function

promise应如下所示:

scope.promise = function ()
{
    var promise = $interval(function ()
    {
        if (scope.state.showDialog === false)
        {
            console.log("Done");

            return true;
        }
    }, 200);

    return promise;
}

然后像这样使用它来激活$interval

scope.promise();

演示片段



angular.module("app", [])

.controller("myController", function($scope, $interval, $timeout) {
  $scope.state = {};
  $scope.state.showDialog = true;

  $timeout(function() {
    $scope.state.showDialog = false;
  }, 2000)

  $scope.promise = function ()
  {
      var promise = $interval(function ()
      {
          if ($scope.state.showDialog === false)
          {
              console.log("Done");
              $interval.cancel(promise);
              
              return $scope.state.showDialog;
          }
          else 
          {
            console.log("False")
          
            return false;
          }
      }, 200);

      return promise;
  }
  
  $scope.promise();
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>

<div ng-app="app">
  <div ng-controller="myController"></div>
</div>
&#13;
&#13;
&#13;

已解决承诺的演示代码段

$interval需要手动解决承诺。

&#13;
&#13;
angular.module("app", [])

.controller("myController", function($scope, $interval, $timeout, $q) {
  $scope.state = {};
  $scope.state.showDialog = true;

  $timeout(function() {
    $scope.state.showDialog = false;
  }, 2000)

  $scope.promise = function ()
  {
      var deferred = $q.defer();
  
      var promise = $interval(function ()
      {
          if ($scope.state.showDialog === false)
          {
              console.log("Done");
              $interval.cancel(promise);
              
              deferred.resolve($scope.state.showDialog);
          }
          else 
          {
            console.log("False")
          }
      }, 200);

      return deferred.promise;
  }
  
  $scope.promise().then(function(response) {
    console.log("Promised has been resolved");
  });
});
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>

<div ng-app="app">
  <div ng-controller="myController"></div>
</div>
&#13;
&#13;
&#13;