Do I always need catch() at the end even if I use a reject callback in all then-ables?

余生颓废 提交于 2019-11-29 18:37:21
Bergi

I am putting catches at the end

That's the typical position for them - you handle all errors that were occurring somewhere in the chain. It's important not to forget to handle errors at all, and having a catch-all in the end is the recommended practise.

even if I use onreject handlers in all .then(…) calls?

That's a bit odd. Usually all errors are handled in a central location (the catch in the end), but of course if you want you can handle them anywhere and then continue with the chain.

Just make sure to understand the difference between an onreject handler in a then and in a catch, and you can use them freely. Still, the catch in the end is recommended to catch errors in the then callbacks themselves.

they are returning empty object in one particular instance atleast.

Then the promise screwed up - it should never reject without a reason. Seems to be caused be the

if ( !app.ajax.url ) {
    console.log("need ajax url");
    promise.reject();
}

in your code that should have been a

if (!app.ajax.url)
    return Promise.reject("need ajax url");

Is a catch necessary for anything unbeknownst?

Not really. The problem is that catch is usually a catch-all, even catching unexpected exceptions. So if you can distinguish them, what would you do with the unexpected ones?

Usually you'd set up some kind of global unhandled rejection handler for those, so that you do not have to make sure to handle them manually at the end of every promise chain.

I think the general question deserves a simple answer without the example.

The pedantic technical answer is 'no', because .catch(e) is equivalent to .then(null, e).

However (and this is a big "however"), unless you actually pass in null, you'll be passing in something that can fail when it runs (like a coding error), and you'll need a subsequent catch to catch that since the sibling rejection handler by design wont catch it:

.then(onSuccess, onFailure); // onFailure wont catch onSuccess failing!!

If this is the tail of a chain, then (even coding) errors in onSuccess are swallowed up forever. So don't do that.

So the real answer is yes, unless you're returning the chain, in which case no.

All chains should be terminated, but if your code is only a part of a larger chain that the caller will add to after your call returns, then it is up to the caller to terminate it properly (unless your function is designed to never fail).

The rule I follow is: All chains must either be returned or terminated (with a catch).

If I remember correctly, catch will fire when your promise is rejected. Since you have the fail callback attached, your catch will not fire unless you call reject function in either your fail or success callback. In other words, catch block is catching rejection in your then method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!