蓝鸟承诺取消 [英] Bluebird Promise Cancellation
问题描述
假设我有以下Promise链:
Say I have the following Promise chain:
var parentPromise = Promise.resolve()
.then(function () {
var condition = false;
if (condition) {
return parentPromise.cancel('valid reason');
} else {
return Promise.resolve()
.then(function () {
var someOtherCondition = true;
if (someOtherCondition) {
console.log('inner cancellation');
return parentPromise.cancel('invalid reason');
}
});
}
})
.catch(Promise.CancellationError, function (err) {
console.log('throwing');
if (err.message !== 'valid reason') {
throw err;
}
})
.cancellable();
上述内容永远不会进入 catch
。
The above never enters the catch
.
如果我们将条件
交换为 true
,则内部取消永远不会被击中,但 catch
仍然没有被触发。
If we swap condition
to true
, the inner cancellation is never hit, but the catch
is still not triggered.
删除 .cancellable
最后,用显式替换
修复问题。我不明白为什么? parentPromise.cancel()
的所有实例抛出新的Promise.CancellationError()
removing the .cancellable
at the end , and replacing all instances of parentPromise.cancel()
with explicit throw new Promise.CancellationError()
"fixes" the problem. What I don't understand is why?
为什么原来的方法不起作用?
Why was the original approach not working?
我正在使用bluebird 2.3.11。
I am using bluebird 2.3.11.
推荐答案
cancellable()
创建可取消的承诺,只有他们抛出 CancellationError
默认情况下,当取消
时,无任何理由调用函数。
cancellable()
creates cancellable promises and only they throw CancellationError
by default, when cancel
function is called with out any reason.
In在你的情况下,你只有在附加了 catch
处理程序后才能做出承诺可取消
。但承诺不是可取消
。所以,取消
函数调用不会引发 Promise.CancellationError
。
In your case, you are making the promise cancellable
only after attaching the catch
handler. But the promise is not cancellable
yet. So, cancel
function call will not raise Promise.CancellationError
.
你需要改变代码的结构,比如这个
You need to change the structure of the code, like this
then(function(..) {
...
})
.cancellable()
.catch(Promise.CancellationError, function (err) {
...
});
注意:我建议以美丽的承诺
构造函数。它类似于ECMA Script 6规范。
Note: I would recommend promising with its beautiful Promise
constructor function. It is similar to the ECMA Script 6 specification.
new Promise(function(resolve, reject) {
...
});
这篇关于蓝鸟承诺取消的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!