Promise和泛型.catch()语句 [英] Promises and generic .catch() statements
问题描述
我正在为我的系统编写一个API,它正在向服务器发送一个XHR并返回一个应该由调用者处理的promise - 到目前为止一直很好。
I'm writing an API for my system, that's sending an XHR to the server and returns a promise that should be handled by the caller - so far so good.
对于每个API调用,我必须使用 .then
和 .catch
调用,但通常(如75%的时间) .catch
引用相同的功能,只需使用 console.error
进行打印。
For each API call I must use a .then
and .catch
calls, but usually (like 75% of the time) the .catch
references the same functionality which simply prints using console.error
.
我的问题是 - 有没有办法为我创建的每个承诺附加一个默认的catch语句?(让我们说打印到控制台),每个保证我想进一步处理拒绝,我会添加另一个 .catch
调用(甚至覆盖它)?
My question is - Is there a way to attach a default catch statement for each promise that I create? (that let's say prints to the console), and for each promise that I would like to further handle the rejection, I would add another .catch
call (or even override it)?
每个调用都有自己的.catch的简化示例: http://jsbin.com/waqufapide/edit?js,控制台
Simplified example where each call has its own .catch: http://jsbin.com/waqufapide/edit?js,console
尝试实现所需行为的非工作版本: http://jsbin.com/nogidugiso/2/edit?js,console
Non working version that tries to implement the desired behavior: http://jsbin.com/nogidugiso/2/edit?js,console
In第二个例子,我返回一个带有附加 catch()
处理程序的promise,而不是只返回 deferred.promise
。
In the second example, instead of just returning deferred.promise
, I return a promise with an attached catch()
handler:
return deferred.promise.catch(function (error) {
console.error(error);
});
然后
catch和然后
在这种情况下调用函数。
Both then
catch and then
functions are called in that case.
我确实知道Q暴露了 getUnhandledReasons()
函数和 onerror
事件,但我真的不想使用 .done()
每个承诺或构建某种计时器/间隔来处理未处理的拒绝列表。
I do realize the Q exposes the getUnhandledReasons()
function and onerror
event, but I don't really want to use .done()
for each promise nor build some kind of timer/interval to handle list of un-handled rejections.
其他库如bluebird暴露 onPossiblyUnhandledRejection
事件,我不得不承认这是一个更好的解决方案,但仍然不是我想要的。
Other libraries such as bluebird expose onPossiblyUnhandledRejection
events, which I have to admit is a bit nicer solution, but still not quite what I'm looking for.
推荐答案
使用NodeJS进程来引发unhandledRejection。如果您不使用NodeJS,则可以使用此解决方法:
Q use NodeJS process to raise unhandledRejection. If you dont use NodeJS, you can use this Workaround:
// Simulating NodeJS process.emit to handle Q exceptions globally
process = {
emit: function (event, reason, promise) {
switch(event)
{
case 'unhandledRejection':
console.error("EXCEPTION-Q> %s", reason.stack || reason)
break;
}
}
}
这篇关于Promise和泛型.catch()语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!