Skip to content

Commit

Permalink
doc: more use-cases for promise events
Browse files Browse the repository at this point in the history
This adds an example of a semi-common promise pattern that could
result in false-positive 'unhandledRejection' events, to help motivate
why there is a dual 'rejectionHandled' event. I anticipate it being
helpful to users who encounter 'unhandledRejection' events that do not
stem from obvious typos such as the JSON.pasre example.

Also cleans up the promise rejection tracking sample. By using a Set
instead of array we can get O(1) deletion. And, fixed indentation there
to align with the rest of the document.
  • Loading branch information
domenic committed Feb 26, 2015
1 parent 14174a9 commit 9010322
Showing 1 changed file with 24 additions and 5 deletions.
29 changes: 24 additions & 5 deletions doc/api/process.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -137,13 +137,29 @@ Here is an example that logs every unhandled rejection to the console
// application specific logging, throwing an error, or other logic here
});

For example, here is a rejection that will trigger the `'unhandledRejection'`
For example, here is a rejection that will trigger the 'unhandledRejection'
event:

somePromise.then(function(res) {
return reportToUser(JSON.pasre(res)); // note the typo
}); // no `.catch` or `.then`

Here is an example of a coding pattern that will also trigger
'unhandledRejection':

function SomeResource() {
// Initially set the loaded status to a rejected promise
this.loaded = Promise.reject(new Error('Resource not yet loaded!'));
}

var resource = new SomeResource();
// no .catch or .then on resource.loaded for at least a turn

To deal with cases like this, which are likely false positives, you can either
attach a dummy `.catch(function() { })` handler to `resource.loaded`,
preventing the 'unhandledRejection' event from being emitted, or you can use
the 'rejectionHandled' event.

## Event: 'rejectionHandled'

Emitted whenever a Promise was rejected and an error handler was attached to it
Expand All @@ -169,15 +185,18 @@ event tells you when the list of unhandled rejections shrinks.
For example using the rejection detection hooks in order to keep a list of all
the rejected promises at a given time:

var unhandledRejections = [];
var unhandledRejections = new Set();
process.on('unhandledRejection', function(reason, p) {
unhandledRejections.push(p);
unhandledRejections.add(p);
});
process.on('rejectionHandled', function(p) {
var index = unhandledRejections.indexOf(p);
unhandledRejections.splice(index, 1);
unhandledRejections.delete(p);
});

You could then record this list in some error log, either periodically or upon
process exit. This would avoid the false positive seen in the above resource
example.

## Signal Events

<!--type=event-->
Expand Down

0 comments on commit 9010322

Please sign in to comment.