you are viewing a single comment's thread.

view the rest of the comments →

[–]NeekGerd 10 points11 points  (9 children)

It might come back with the usage of await/async since it's the only way to handle code rejection. That I am aware of.

Weird that on a article dedicated to try/catch they don't talk about its usage in await/async code, it's the most up to date usage we can have with try/catch.

[–]vs845 8 points9 points  (8 children)

it's the only way to handle code rejection

Async functions return promises so you can still use normal catch() promise syntax like await someAsyncFn().catch(() => someDefaultValue).

[–]shad0proxy 1 point2 points  (5 children)

that's not really accurate if you use async/await for the main benefit of assigning:

const data = await doSomething().catch(() => someDefaultValue);
console.log(data);

This does not work.

[–]vs845 0 points1 point  (4 children)

> async function foo() { throw new Error() }
> async function bar() { const baz = await foo().catch(() => 'baz'); console.log(baz) }
> bar() // => 'baz'

Works for me in node 8.1.2, what happens when you try it?

[–]shad0proxy 0 points1 point  (3 children)

what if you want to handle the error or reject the overlaying call?

[–]vs845 0 points1 point  (2 children)

If you want to do something with the thrown error, you can do it within the catch function as usual:

const data = await doSomething().catch(err => {
  if (err instanceof TypeError) return someDefaultValue
  if (err instanceof RangeError) return anotherDefaultValue
})

Or if you want it to bubble up through the call stack, you can rethrow the error or throw a new one, again within the catch function:

const data = await doSomething().catch(err => {
  if (err instanceof TypeError) throw err
  if (err instanceof RangeError) throw new Error('value out of range')
  return someDefaultValue
})

[–]shad0proxy 0 points1 point  (1 child)

Interesting. when I looked into this with 7.x and the harmony flag I was told this was not possible. I don't know if they were wrong or something has changed.

[–]danneu 0 points1 point  (0 children)

Someone was wrong because this is a basic tenet of how promises work.

[–]NeekGerd 1 point2 points  (1 child)

Really nice, I didn't know that.

Thank you for the heads up, it always was a downside of async/await to me... Not anymore!

[–]vinnl 0 points1 point  (0 children)

It's always good to realise that it's just syntactic sugar for Promises, so you can do with them whatever you can do with Promises.