0

I have two promises running at the end of the main code, but one runs in the catch using an arrow function and the other runs directly, do you know the difference between one and the other?

const main = async () => {
  const promisseTeste1 = () => new Promise((resolve, reject) => {
    reject("ERRO")
  });

  const promisseTeste2 = () => new Promise((resolve, reject) => {
    promisseTeste1().then().catch(reject)
  });

  // Method 1
  promisseTeste2().then().catch(console.log)
  
  // Method 2
  promisseTeste2().then().catch(e => console.log(e))
}

main()

I wanted to know if there is any performance issue or even a possible problem that may occur using method 1.

Roamer-1888
  • 19,138
  • 5
  • 33
  • 44

1 Answers1

2

If you're using console.log, then in any browser that isn't utterly obsolete, there won't be an issue.

In some very old browsers, having console.log being called with something other than a calling context of console was an issue - but many would consider this not to be something worth worrying about.

For the general case of passing an already-declared function instead of creating an anonymous inline function, one potential gotcha is (similar to previously) the this value inside the callback if passing in / calling an object method. The this value will be the object when invoking it inline, and globalThis (or undefined in strict mode) if passing it in directly.

const obj = {
  prop: 'val',
  method() {
    console.log(this.prop);
  }
};

const main = async () => {
  // Method 1
  Promise.reject().then().catch(obj.method)
  
  // Method 2
  Promise.reject().then().catch(e => obj.method(e))
}

main()

Although not related to the core of your question, as you see in the above snippet, I've avoided the explicit Promise construction antipattern, and recommend you do the same.

if there is any performance issue

Not remotely. Unless you're in a tight loop or doing multiple DOM manipulations, performance of a segment of code almost certainly isn't even worth considering - better to focus on code readability and maintainability.

For the even more general issue of doing .method(callback) instead of .method(value => callback(value)), be wary of functions whose behavior changes depending on how many arguments are passed in (which is why .map(parseInt) doesn't work) Luckily this isn't an issue with .then and .catch, because they only ever pass one argument to the callback.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320