express-async-handler icon indicating copy to clipboard operation
express-async-handler copied to clipboard

Description of this project in README.md is unclear

Open rjmunro opened this issue 3 years ago • 4 comments

I'm reviewing code that uses this project, and it's unclear from the README what it is needed for.

It doesn't seem to be middleware as such, it seems something you wrap around your functions to turn async requests into ones that call the next() method. I thought that express could already do this built in, so why is this needed? Does express not try ... catch async methods or something? Is this not needed any more - is it legacy from before express did async methods (and / or promises) natively?

It would be good if the README had a bit more explanation of why you need this, compared to normal:

Why do you need:

app.get('/foo', asyncHandler(async (req, res) => {
  ...
}));

When you can just do:

app.get('/foo', async (req, res) => {
  ...
});

rjmunro avatar Oct 15 '21 16:10 rjmunro

Does express not try ... catch async methods or something?

☝️

willwillems avatar Nov 03 '21 10:11 willwillems

'For errors returned from asynchronous functions invoked by route handlers and middleware, you must pass them to the next()' So basically this call next in every route so express can throw the errors, otherwise the server stays hanging

You can try throwing an error inside an asynchronous functions without wrapping your function inside asyncHandler() and see what happens.

ralph993 avatar Dec 02 '21 22:12 ralph993

@rjmunro This post provides a great description of why I think this project is useful. https://zellwk.com/blog/async-await-express/

abierbaum avatar Jan 04 '22 14:01 abierbaum

Starting with Express 5, route handlers and middleware that return a Promise will call next(value) automatically when they reject or throw an error. For example:

app.get('/user/:id', async function (req, res, next) {
  var user = await getUserById(req.params.id)
  res.send(user)
})

☝️ Doesn't this make the NPM package obsolete now? Quoted from here

--- edit ---

Ah, I see Express 5 is not released as a stable version yet.

0x80 avatar Jan 19 '22 10:01 0x80