【问题标题】:Confusion about how the promise returned by $interval works compared to $timeout in Angular与 Angular 中的 $timeout 相比,$interval 返回的承诺如何工作的困惑
【发布时间】:2014-09-25 20:36:31
【问题描述】:

我在理解 $interval 返回的承诺如何在 Angular 中工作时遇到问题。

假设在下面的示例中,我们有一个简单的“api”工厂,其中包含一个名为“getStuff”的方法,该方法返回一个包含一项的数组。我们还有一个控制器在那个工厂调用 $timeout:

angular.module("app",[])
  .factory('api', function(){
    return {
      getStuff: function() {      
        return ["stuff"];
      } 
    };   
  })
  .controller('appCtrl', function($scope, $timeout, api){
    $timeout(api.getStuff, 1000)
      .then(function(response){
        console.log(response);
      });
  })

这将在 1 秒后在控制台中记录 '["stuff"]',这很棒。

假设我想通过将 $timeout 替换为 $interval 来每秒调用一次该方法。现在什么都没有发生:

angular.module("app",[])
  .factory('api', function(){
    return {
      getStuff: function() {      
        return ["stuff"];
      } 
    };   
  })
  .controller('appCtrl', function($scope, $interval, api){
    $interval(api.getStuff, 1000)
      .then(function(response){
        console.log(response);
      });
  })

在这种情况下,$timeout 和 $interval 有什么不同?

感谢所有帮助!

【问题讨论】:

    标签: angularjs intervals angularjs-service


    【解决方案1】:

    将计数值添加到 DIMM Reaper 在对 Christophe L 的回答的评论中提供的示例中:

    var app = angular.module("app", []);
    
    app.run(function ($interval) {
        console.log('This fiddle will self destruct...');
        
        var timer = $interval(function (count) {
            console.log('tick... ' + count);
        }, 500, 4, false);
        
        timer.then(function(res) {
            console.log("BOOM! " + res);
        });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"></script>
    
    <body ng-app="app">
    </body>

    输出:

    This fiddle will self destruct...
    tick... 1
    tick... 2
    tick... 3
    tick... 4
    BOOM! 4
    

    最终结果为最终计数。

    【讨论】:

      【解决方案2】:

      你可以对$interval返回的promise做的唯一事情就是取消它(停止它的执行):

      var handle = $interval(someFunc, 1000);
      ...
      $interval.cancel(handle);
      

      您的代码应该如下所示:

      app.controller('appCtrl', function($scope, $interval, api) {
          $interval(function() {
              console.log(api.getStuff());
          }, 1000);
      });
      

      看中了一切,并看到一切协同工作:

      app.controller('appCtrl', function($scope, $interval, $timeout, api) {
          var handle = $interval(function() {
              console.log(api.getStuff());
          }, 1000);
      
          $timeout(function() {
              $interval.cancel(handle);
          }, 5000);
      });
      

      【讨论】:

      • 我不同意你的第一点,$interval 返回的承诺只能用于取消计时器。这是一个成熟的承诺:它会在计时器到期时得到解决(假设您设置了最大时间),而当您调用 $interval.cancel() 时它会被拒绝。 Here's a fiddle.
      猜你喜欢
      • 2018-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 2021-08-22
      相关资源
      最近更新 更多