HP4k1h5
HP4k1h5

Reputation: 1

return inside a try/catch vs return in a .catch

Why is the behavior of return different inside the catch of try/catch vs inside .catch ?

function promise(call, params) {
  return new Promise((keep, brk) => {
    brk(2)
    keep(1)
  })
}

async function a() {
  try {
   var r = await promise()
  } catch (e) {
    return console.error('a catch e', e)
  } 
  console.log('a after catch')
  return r
}

async function b() {
  let r = await promise().catch(e => {
    return console.error('b catch e', e)
  })
  console.log('b after catch')
  return r
}

a().then(v => console.log('a', v))
b().then(v => console.log('b', v))

returns

a catch e 2
b catch e 2
a undefined
b after catch
b undefined

Upvotes: 0

Views: 79

Answers (1)

Anis R.
Anis R.

Reputation: 6902

The main difference is that, as pointed out by @Berji's comment, your catch's return statement does not have the same enclosing parent function in a and b.

  • In a, it is enclosed directly inside the function a

  • In b, it is enclosed inside an anonymous function that is itself enclosed inside the function b.

This means that in the latter case, it is the anonymous function inside b that is returning, not b itself.

This explains why in your output, b after catch is being printed but not a after catch: a is returning before the console log gets called.

Upvotes: 3

Related Questions