Skip to content

Instantly share code, notes, and snippets.

@MaxXx1313
Created July 21, 2020 13:14
Show Gist options
  • Save MaxXx1313/0b2623d80bdb54efd76d2ed386bafcce to your computer and use it in GitHub Desktop.
Save MaxXx1313/0b2623d80bdb54efd76d2ed386bafcce to your computer and use it in GitHub Desktop.
Can return promise from express middleware
/**
* Can return promise from express middleware
* router.get('/pets', expressPromise(req => {
return db.getAll().then(... do some stuff...); // <it's a Promise!
}));
*/
export function expressPromise(worker: (req: Request) => any) {
return (req: Request, res: Response, next: NextFunction) => {
// wrap with "Promise.resolve()", so if an exception is thrown in "worker" it will be handled with 'catch'
Promise.resolve()
.then(() => worker(req))
.then(res.send.bind(res))
.catch(next);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment