什么更快:try catch vs Promise [英] What is faster: try catch vs Promise

查看:23
本文介绍了什么更快:try catch vs Promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听到这样一种意见,你应该完全避免使用 try/catch,因为它需要很多资源.那么承诺错误处理速度会更快吗?或者根本没有关系?

I heard such an opinion that you should avoid usage of try/catch at all because it takes many resources. So could the promise error handling to be faster? Or it does not matter at all?

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 不适用于内部的异步代码.我只是想知道是否有任何理由因为性能问题而避免尝试/捕获?上面的两种方法有什么区别吗?

UPD: I know that try/catch won't work with async code inside. I'm just wondering if there any reasons to avoiding of try/catch because of performance issues? And is there any difference between the two approaches above?

UPD2:试图与我的马赛跑 :) https://jsperf.com/try-catch-vs-promise

UPD2: Tried to race my horses :) https://jsperf.com/try-catch-vs-promise

推荐答案

你应该将 Promise 用于异步函数,而不是别的.不要滥用它们作为错误 monad,那会浪费资源,而且它们固有的异步性会使一切变得更加麻烦.

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 every­thing more cumbersome.

当你有同步代码时,使用try/catch进行异常处理.

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;
}

如果您已经有承诺代码,您可以在某些情况下避免这种情况:当您希望异常拒绝承诺时.在这些情况下,您应该让 Promise 的内置错误处理完成它的工作,而不是通过额外但毫无意义的 try/catch 层使一切复杂化:

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 vs Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆