Hacker News new | ask | show | jobs
by brwsr 3021 days ago
> Avoid try/catch

haha, async await needs that by design!

1 comments

It's not required, you can use .catch since it's just normal promises:

const result = await doStuff().catch(errorHandler);

So what do you think your result variable contains in the event that the promise is rejected? Is this semantically equivalent to try/catch?
(async () => { const result = await Promise.reject(1).catch(e => e); return result; })()

// =>Promise {<resolved>: 1}

As you can see, the variable contains a promise returned by the .catch. It's not equivalent to try/catch (in that case the variable won't be defined for one thing), but it does allow for error handling without using try/catch if one is inclined to do so.

In practice, I've been using async/await extensively in Node.js/Express, and I'm yet to write a single try/catch. In Express, I simply use a wrapper function that catches promise rejections and siphons them to error handling middleware:

const asyncIt = fn => (req, res, next, ...args) => fn(req, res, next, ...args).catch(next);