Created
December 25, 2014 22:31
-
-
Save joepie91/e4cd0f2c84ea2f303bb2 to your computer and use it in GitHub Desktop.
Using Express.js with Promises
This file contains 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
/* 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