4 ms·
> Avoid try/catch haha, async await needs that by design!
by brwsr 9y ago
> Avoid try/catch
haha, async await needs that by design!
- maga 9y agoIt's not required, you can use .catch since it's just normal promises: const result = await doStuff().catch(errorHandler);
- dcherman 9y agoSo what do you think your result variable contains in the event that the promise is rejected? Is this semantically equivalent to try/catch?
- maga 9y ago(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);