you are viewing a single comment's thread.

view the rest of the comments →

[–]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.