我听到这样的意见,你应该完全避免使用 try/catch,因为它占用很多资源。那么 promise 错误处理可以更快吗?还是根本不重要?
function f(somethingDangerous) {
return new Promise((resolve, reject) => {
// try {
// somethingDangerous();
// resolve();
// } catch (err) {
// reject(err);
// }
// VS
somethingDangerous();
resolve();
}).catch((err) => {
console.error('Catched: ' + err);
});
}
f(() => {throw 'DANGEROUS THING';});
UPD:我知道 try/catch 不能与内部的异步代码一起使用。我只是想知道是否有任何理由因为性能问题而避免使用 try/catch?以上两种方法有什么区别吗?
UPD2:试图让我的马赛跑:) https://jsperf.com/try-catch-vs-promise
最佳答案
您应该仅将Promises 用于异步函数,而不是其他任何东西。不要将它们滥用为错误 monad,那会浪费资源,而且它们固有的异步性会使一切变得更加麻烦。
当您有同步代码时,使用try
/catch
进行异常处理。
/* Wrong */
return new Promise(function(resolve, reject) {
resolve(x / y);
}).catch(err => NaN)
/* Right */
try {
return x / y;
} catch(e) {
return NaN;
}
如果您已经有了 promise 代码,您可以在某些情况下避免这种情况:当您希望异常拒绝 promise 时。在这些情况下,你应该让你的 promise 的内置错误处理完成它的工作,而不是通过额外但毫无意义的 try
/catch
层使一切复杂化:
/* 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();
}).…
关于javascript - 什么更快 : try catch vs Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42648956/