Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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: 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: Tried to race my horses :) https://jsperf.com/try-catch-vs-promise

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
335 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...