Skip to content

Instantly share code, notes, and snippets.

@tomardern
Created March 20, 2018 21:42
Show Gist options
  • Save tomardern/76ed93dc83a84074e353cb06e103b79b to your computer and use it in GitHub Desktop.
Save tomardern/76ed93dc83a84074e353cb06e103b79b to your computer and use it in GitHub Desktop.
Node Express Promise
/**
* Catch all promise function
* @param {Object} func
* @param {Request} request
* @param {Response} response
*/
const fn = (func, request, response) => {
console.log(request.method, request.originalUrl);
const params = Object.assign({}, request.params, request.query, request.body);
try {
func(params)
.then(output => response.status(200).send(output))
.catch(err => { console.error(err); response.status(500).send({ error: err }); });
} catch (e) {
console.error(e);
response.status(500).send({ error: e.toString() });
}
};
/* A basic promise function */
const doSomethingCool = () => {
return doAjax()
.then(() => doAjax(2))
};
/* Used similar to the below: */
app.get('/something-here', (req, res, next) => fn(doSomethingCool, req, res));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment