Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Using Express.js with Promises
/* Without using express-promise-router...
* If either of the two Promise-returning methods ends up failing (ie. rejecting),
* an uncaught exception will be printed to stdout, and the client will never get
* a response - instead, they'll be stuck on an infinitely loading page.
*/
express = require("express").router();
router.get("/", function(req, res) {
Promise.try(function(){
return doSomethingThatReturnsAPromise();
}).then(function(result){
return doSomethingElsePromisey(result);
}).then(function(otherResult){
res.send("The result was " + otherResult);
});
});
/* Using express-promise-router...
* If either of the two Promise-returning methods ends up failing (ie. rejecting),
* the error will be caught transparently by the router, and it will be passed down
* through the regular Express error handling process; that is, passed on to the
* error-handling middleware you have specified.
* Note how it now *returns* the Promise - this is required.
*/
express = require("express-promise-router");
router.get("/", function(req, res) {
return Promise.try(function(){
return doSomethingThatReturnsAPromise();
}).then(function(result){
return doSomethingElsePromisey(result);
}).then(function(otherResult){
res.send("The result was " + otherResult);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.