Should I refrain from handling Promise rejection asynchronously?

I have just installed Node v7.2.0 and learned that the following code:

var prm = Promise.reject(new Error('fail'));

results in this message:;

(node:4786) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: fail
(node:4786) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I understand the reasoning behind this as many programmers have probably experienced the frustration of an Error ending up being swallowed by a Promise. However then I did this experiment:

var prm = Promise.reject(new Error('fail'));

setTimeout(() => {
    prm.catch((err) => {
        console.log(err.message);
    })
},
0)

which results in:

(node:4860) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: fail
(node:4860) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:4860) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
fail

I on basis of the PromiseRejectionHandledWarning assume that handling a Promise rejection asynchronously is/might be a bad thing.

But why is that?

Answers:

Answer

"Should I refrain from handling Promise rejection asynchronously?"

Those warnings serve an important purpose but to see how it all works see those examples:

Try this:

process.on('unhandledRejection', () => {});
process.on('rejectionHandled', () => {});

var prm = Promise.reject(new Error('fail'));

setTimeout(() => {
    prm.catch((err) => {
        console.log(err.message);
    })
}, 0);

Or this:

var prm = Promise.reject(new Error('fail'));
prm.catch(() => {});

setTimeout(() => {
    prm.catch((err) => {
        console.log(err.message);
    })
}, 0);

Or this:

var var caught = require('caught');
var prm = caught(Promise.reject(new Error('fail')));

setTimeout(() => {
    prm.catch((err) => {
        console.log(err.message);
    })
}, 0);

Disclaimer: I am the author of the caught module (and yes, I wrote it for this answer).

Rationale

It was added to Node as one of the Breaking changes between v6 and v7. There was a heated discussion about it in Issue #830: Default Unhandled Rejection Detection Behavior with no universal agreement on how promises with rejection handlers attached asynchronously should behave - work without warnings, work with warnings or be forbidden to use at all by terminating the program. More discussion took place in several issues of the unhandled-rejections-spec project.

This warning is to help you find situations where you forgot to handle the rejection but sometimes you may want to avoid it. For example you may want to make a bunch of requests and store the resulting promises in an array, only to handle it later in some other part of your program.

One of the advantages of promises over callbacks is that you can separate the place where you create the promise from the place (or places) where you attach the handlers. Those warnings make it more difficult to do but you can either handle the events (my first example) or attach a dummy catch handler wherever you create a promise that you don't want to handle right away (second example). Or you can have a module do it for you (third example).

Avoiding warnings

Attaching an empty handler doesn't change the way how the stored promise works in any way if you do it in two steps:

var prm1 = Promise.reject(new Error('fail'));
prm1.catch(() => {});

This will not be the same, though:

var prm2 = Promise.reject(new Error('fail')).catch(() => {});

Here prm2 will be a different promise then prm1. While prm1 will be rejected with 'fail' error, prm2 will be resolved with undefined which is probably not what you want.

But you could write a simple function to make it work like a two-step example above, like I did with the caught module:

var prm3 = caught(Promise.reject(new Error('fail')));

Here prm3 is the same as prm1.

See: https://www.npmjs.com/package/caught

2017 Update

See also Pull Request #6375: lib,src: "throw" on unhandled promise rejections (not merged yet as of Febryary 2017) that is marked as Milestone 8.0.0:

Makes Promises "throw" rejections which exit like regular uncaught errors. [emphasis added]

This means that we can expect Node 8.x to change the warning that this question is about into an error that crashes and terminates the process and we should take it into account while writing our programs today to avoid surprises in the future.

See also the Node.js 8.0.0 Tracking Issue #10117.

Answer

I assume that handling a Promise rejection asynchronously is a bad thing.

Yes indeed it is.

It is expected that you want to handle any rejections immediately anyway. If you fail to do (and possibly fail to ever handle it), you'll get a warning.
I've experienced hardly any situations where you wouldn't want to fail immediately after getting a rejection. And even if you need to wait for something further after the fail, you should do that explicitly.

I've never seen a case where it would be impossible to immediately install the error handler (try to convince me otherwise). In your case, if you want a slightly delayed error message, just do

var prm = Promise.reject(new Error('fail'));

prm.catch((err) => {
    setTimeout(() => {
        console.log(err.message);
    }, 0);
});

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.