What is faster: try catch vs Promise
You should use Promises only for asynchronous functions and nothing else. Do not abuse them as an error monad, that would be a waste of resources and their inherent asynchrony will make everything more cumbersome.
When you have synchronous code, use try
/catch
for exception handling.
/* Wrong */
return new Promise(function(resolve, reject) {
resolve(x / y);
}).catch(err => NaN)
/* Right */
try {
return x / y;
} catch(e) {
return NaN;
}
If you already have promise code, you can avoid that in certain situations: when you want the exception to reject the promise. In those cases you should just let the builtin error handling of your promises do its job, and not complicate everything by an additional but pointless try
/catch
layer:
/* Wrong */
new Promise(function(resolve, reject) {
try { // when used synchronous in the executor callback
…
resolve(somethingSynchronous());
} catch (e) {
reject(e);
}
});
/* Right */
new Promise(function(resolve, reject) {
…
resolve(somethingExceptionally());
});
/* Wrong */
….then(function(res) {
try {
…
return somethingExceptionally();
} catch(e) {
return Promise.reject(e);
}
}).…
/* Right */
….then(function(res) {
…
return somethingExceptionally();
}).…
try/catch
idiom works very well when you have fully synchronous
code, but asynchronous
operations render it useless, no errors will be caught. i.e., the function will begin its course while the outer stack runs through and gets to the last line without any errors. If an error occurs at some point in the future inside asynchronous function – nothing will be caught.
When we use Promise
s, “we’ve lost our error handling”, you might say. That’s right, we don’t need to do anything special here to propagate error because we return a promise and there’s built in support for error flow.