问题描述
如何拒绝延迟的承诺:
const removeDelay = Promise.delay(5000).then(() => {
removeSomething();
});
//Undo event - if it is invoked before 5000 ms, then undo deleting
removeDelay.reject(); // reject is not a method
推荐答案
Bluebird v3
我们不再需要将Promise声明为可取消"(文档):
We no longer need to declare a Promise as 'cancellable' (documentation):
仅凭承诺致电cancel
:
const promise = new Promise(function (_, _, onCancel) {
onCancel(function () {
console.log("Promise cancelled");
});
});
promise.cancel(); //=> "Promise cancelled"
您可能已经注意到,cancel
方法不再接受取消的原因作为参数.取消所需的逻辑可以在提供给onCancel
的函数中声明,该函数提供给Promise构造函数执行器的第三个参数.或在finally
回调中,因为取消Promise时也不会将其视为错误.
As you may have noticed, the cancel
method no longer accepts the reason for cancellation as an argument. Logic required on cancellation can be declared within a function given to onCancel
, the third argument given to a Promise constructor executor. Or within a finally
callback, as it is also not considered an error when a Promise is cancelled.
修订示例:
const removeDelay = Promise
.delay(5000)
.then(() => removeSomething());
removeDelay.cancel();
______
Pre Bluebird v3
看看 Promise#cancellable
的文档:
Take a look at the documentation for Promise#cancellable
:
我们可以这样使用它:
const removeDelay = Promise
.delay(5000)
.cancellable() // Declare this Promise as 'cancellable'
.then(() => removeSomething());
.catch(err => console.log(err)); // => 'Reason for cancel'
removeDelay.cancel('Reason for cancel');
这篇关于取消延迟的蓝鸟承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!