Created
March 20, 2018 21:42
-
-
Save tomardern/76ed93dc83a84074e353cb06e103b79b to your computer and use it in GitHub Desktop.
Node Express Promise
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
/** | |
* 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