Created
July 21, 2020 13:14
-
-
Save MaxXx1313/0b2623d80bdb54efd76d2ed386bafcce to your computer and use it in GitHub Desktop.
Can return promise from express middleware
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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