【问题标题】:Stopping an $interval function with a promise attached停止一个附加了承诺的 $interval 函数
【发布时间】:2016-02-17 01:26:05
【问题描述】:

在角度控制器内部,我试图停止间隔。如果有一个 .then 承诺链接到它,是否无法停止间隔?

为什么stopCount函数在这里起作用

var stop = $interval(function(){
    console.log('testing interval');
  }, 1000);

$scope.stopCount = function(){
  $interval.cancel(stop);
}

但这里没有.then

var stop = $interval(function(){
    console.log('testing interval');
  }, 1000)
  .then(function(){
     console.log('complete')
  });

$scope.stopCount = function(){
  $interval.cancel(stop);
}

提前致谢!

【问题讨论】:

  • $timeout 将返回一个您可以调用 .then 的承诺,因为在某种意义上它就像一个承诺。它在一定时间后做某事。虽然间隔不同,但它一直在继续。所以一旦你启动它,你唯一能做的就是停止它
  • 如果您想在 1 秒后执行 console.log,那么只需插入 $timeout 而不是 $interval 就可以了 :)
  • 感谢您的解释!那么有没有办法在取消间隔后运行函数呢?
  • 想想这个。 .then 方法返回一个新的承诺。所以你试图阻止新的承诺,而不是原来的承诺。

标签: javascript angularjs setinterval


【解决方案1】:

试试这个!

// The problem is that stop is not storing the promise of $interval
// It's storing the promise returned by the .then method
var stop = $interval(function(){
  console.log('testing interval');
}, 1000)
.then(function(){
  console.log('complete')
});

$scope.stopCount = function(){
  $interval.cancel(stop);
}


// Try this
// Now stop is using $intervals promise,
// not .then. We'll call .then separately below
var stop = $interval(function(){
  console.log('testing interval');
}, 1000);

// Now we can cancel the 'stop' interval below
// This promise has to have a success callback
// AND an error callback.
stop.then(function(){
  console.log('complete')
}, function(err) {
  console.log('Uh oh, error!', err);
});

$scope.stopCount = function(){
  $interval.cancel(stop);
}

【讨论】:

  • 它确实停止了间隔,但是当我停止时我没有看到“完成”被记录。
  • 嗯,这就是$timeout和$interval的区别。 $interval 应该在间隔的每次迭代中调用你的 console.log 一次。 $timeout 只会在完成后调用你的 console.log
  • 听起来你甚至没有得到那个。此代码的结果应该是每秒记录一次“完成”。
  • 我确实每秒得到一次测试间隔
  • 但不完整?他们都应该被记录,首先测试,然后完成。在每次迭代中
【解决方案2】:

好吧,所以你显然不完全了解承诺......这个dosent起作用的原因:

var stop = $interval(function(){
    console.log('testing interval');
  }, 1000)
  .then(function(){
     console.log('complete')
  });

$scope.stopCount = function(){
  $interval.cancel(stop);
}

是因为你有两个承诺...第一个是毫秒,即 1000/ 1 秒。另一个是 .then() 承诺。你不能在一个函数中使用两个 Promise。

如果您查看文档 here,您会看到 $interval 的语法是:

$interval(fn, delay, [count], [invokeApply], [Pass]);

取消函数的语法是这样的

$interval.cancel([promise]);

【讨论】:

  • $interval 如何是毫秒的承诺?你只能取消它。另一方面,您绝对可以在同一个 Promise 上使用多个回调。除非我误解了你的意思?
  • 我不是在谈论同一个承诺的多个回调。我说多重承诺。 @DustinStiles
  • 那部分完全正确。我仍然不明白有两个承诺。 $interval 返回一个承诺,这是代码中唯一的承诺。 $interval 返回一个承诺 (.then) 是这样吗?有什么我没看到的吗?
  • 我想我明白你在说什么,写下我自己的答案澄清了:)
  • 虽然在一个函数中使用两个 Promise 有点令人困惑。这是真的,但不是 OP 的代码发生了什么。我想你的意思是,你不能在同一个变量中存储两个 Promise :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-18
  • 2019-09-08
  • 2014-12-29
  • 2017-05-16
相关资源
最近更新 更多