更快的方法:尝试捕获与承诺 [英] What is faster: try catch vs Promise

查看:60
本文介绍了更快的方法:尝试捕获与承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听到这样的观点,您应该完全避免使用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不适用于异步里面的代码。我只是想知道由于性能问题,是否有任何避免使用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

推荐答案

对于异步功能,您应该仅对Promises使用 ,而不能使用其他任何功能。不要把它们当作错误的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;
}

Iff ,您已经有承诺代码,可以在某些情况下避免这种情况:当您希望例外情况拒绝承诺时。在这种情况下,您应该让承诺的内置错误处理工作发挥作用,而不用额外但毫无意义的 try / catch 层:

Iff 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();
}).…

这篇关于更快的方法:尝试捕获与承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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