Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

5
  • Is there anyway to create this function as an express middleware and use it it app.use(..)? Commented Apr 7, 2020 at 19:32
  • @SuleymanSah - Two ways. You can put this above code (without the app.useP = part) in a module, export the function, then after you create your new router, you do router.useP = require('./asyncWrapper'), then use router.useP(...). Or second, you could modify the router prototype in just one place so it was automatically added for all routers. It would take more investigation to figure out exactly how you modify that prototype since Express only exposes a factory function, not the actual class. Commented Apr 7, 2020 at 19:35
  • Ok after putting it in a module, and using in my router like this router.useP = require('./asyncWrapper'); how can I use it in my router.get(...) or router.post(...)? Commented Apr 7, 2020 at 19:40
  • @SuleymanSah - FYI, I corrected a few typos in my answer and I'm working on a more generic implementation that hooks into the routers and app more automatically. Will add to my answer when I get it to work. Commented Apr 7, 2020 at 21:55
  • 1
    @SuleymanSah - I added a module form to my answer that modifies the prototypes for both app and router and it also works for .getP(), ` .postP()`, etc... so you can use any of the http verbs on app or router. Commented Apr 7, 2020 at 22:16