Skip to content

Instantly share code, notes, and snippets.

@slowtick
Last active December 4, 2020 03:17
Show Gist options
  • Save slowtick/4404d756c44dcdbbf89e0ce3201d97bd to your computer and use it in GitHub Desktop.
Save slowtick/4404d756c44dcdbbf89e0ce3201d97bd to your computer and use it in GitHub Desktop.
express js wrapper for using async function to handle requests
import express from 'express';
type AsyncRouteHandlerType = (request: express.Request, response: express.Response, next: express.NextFunction) => Promise<void>;
/**
* Wraps async router function, calls the function with router args and invokes next function on exceptions.
* @example
* import express from 'express';
* const router = express.Router();
* router.get('/thing/list', asyncRouteHandler(listThings));
*
* async function listThings(request: express.Request, response: express.Response, next: express.NextFunction): Promise<void> {
* // thing a magic here
* }
* @param asyncRouter async/await express route handler (function that takes express router arguments and returns a Promise)
*/
export const asyncRouteHandler = (asyncRouter: AsyncRouteHandlerType) =>
(request: express.Request, response: express.Response, next: express.NextFunction): void => { asyncRouter(request, response, next).catch(next); };
// above function is curried https://stackoverflow.com/a/32787782/6881065 - in detail its same code as below
// const asyncRouteHandlerExplained = function (asyncHandler: AsyncRouteHandlerType) {
// return function (request: express.Request, response: express.Response, next: express.NextFunction): void {
// asyncHandler(request, response, next).catch(next);
// };
// };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment