Keep track of unhandled rejected Q promises
There's a rule in Q (and other promise libs implementing .done()) that avoids a lot of debugging frustration:
The Golden Rule of
donevs.thenusage is: eitherreturnyour promise to
someone else, or if the chain ends with you, calldoneto terminate it.
After some practice it's easy and natural to follow it but, as any other manual task, it's still error-prone.
Thankfully Q keeps tracks of the unhandled failed promises so we have the chance to do something with them. Because a promise can be handled long after being created, there's only one moment when we know for sure a promise was unhandled: when the page unloads.
With this in mind, for example, we can throw the first unhandled error in the event loop so this would be handled like any other error being thrown outside of a promise:
// Throw the first unhandled rejected Q promise
window.addEventListener('beforeunload', function () {
Q.getUnhandledReasons().forEach(function (error) {
throw error;
});
});
Usually by default the browser will show the error in the console, but you can do whatever you want by overriding window.onerror.
Extra notes
Written by Francesc Rosàs
Related protips
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside