蓝鸟承诺取消

编程入门 行业动态 更新时间:2024-10-22 23:35:59
本文介绍了蓝鸟承诺取消的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有以下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) { ... });

更多推荐

蓝鸟承诺取消

本文发布于:2023-11-25 02:47:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628017.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:蓝鸟

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!