【发布时间】:2014-08-12 21:43:24
【问题描述】:
使用https://github.com/kriskowal/q 库,我想知道是否可以这样做:
// Module A
function moduleA_exportedFunction() {
return promiseReturningService().then(function(serviceResults) {
if (serviceResults.areGood) {
// We can continue with the rest of the promise chain
}
else {
performVerySpecificErrorHandling();
// We want to skip the rest of the promise chain
}
});
}
// Module B
moduleA_exportedFunction()
.then(moduleB_function)
.then(moduleB_anotherFunction)
.fail(function(reason) {
// Handle the reason in a general way which is ok for module B functions
})
.done()
;
基本上,如果服务结果不好,我想处理模块 A 中的故障,使用特定于模块 A 内部的逻辑,但仍然跳过承诺链中剩余的模块 B 函数。
跳过模块 B 函数的明显解决方案是从模块 A 中抛出错误/原因。但是,我需要在模块 B 中处理它。理想情况下,我希望在不需要任何额外代码的情况下这样做模块 B。
这很可能是不可能的 :) 或者违反 Q 的一些设计原则。
在这种情况下,您会建议什么样的替代方案?
我想到了两种方法,但都有各自的缺点:
-
从模块 A 中抛出一个特定的错误并将特定的处理代码添加到模块 B:
.fail(function(reason) { if (reason is specificError) { performVerySpecificErrorHandling(); } else { // Handle the reason in a general way which is ok for module B functions } }) -
在模块 A 中执行自定义错误处理,然后在处理错误后,抛出一个虚假的拒绝原因。在模块B中,添加一个忽略虚假原因的条件:
.fail(function(reason) { if (reason is fakeReason) { // Skip handling } else { // Handle the reason in a general way which is ok for module B functions } })
解决方案 1 需要将模块 A 的特定代码添加到模块 B。
解决方案 2 解决了这个问题,但整个假拒绝方法似乎非常骇人听闻。
您能推荐其他解决方案吗?
【问题讨论】:
-
让我们玩个小游戏——写下如果根本不涉及任何承诺,你将如何在同步代码中完成此任务?
-
感谢您的建议:DI 意识到,在同步代码中,我可能会从模块 A 函数返回一个“shouldContinue”布尔值并在模块 B 中处理它。在基于承诺的代码中,它看起来像一个 hack ,但事后看来,它远没有假错误和诸如此类的东西那么 hacky :)
-
不要忘记使用
.spread来返回一个数组并将其参数作为参数查看,以便能够对多个变量做出反应:Q([false,{}]).spread(function(success,data){ /* code here */})
标签: javascript node.js promise q