Permalink
Browse files

more refactor for readability

breaking out of nesting promises too much
  • Loading branch information...
nrstott committed Feb 6, 2013
1 parent c5e58e8 commit e518294ec1f0ea4fe222d745d64d09eff36fd477
Showing with 31 additions and 34 deletions.
  1. +31 −34 lib/router.js
View
@@ -74,16 +74,12 @@ function Router(config, notFoundApp) {
return this;
};
- return Q.whenCall(function() {
- return router.respond(require('./request')(this, req));
- }, function(resp) {
- if (util.no(resp)) {
- return router.nextApp(req);
+ return when(req, function(req) {
+ try {
+ return router.respond(require('./request')(this, req));
+ } catch (err) {
+ return util.reject(err);
}
-
- return resp;
- }, function(err) {
- return Q.reject(err);
});
};
@@ -177,38 +173,39 @@ Router.prototype.handler = function(verb, path) {
return null;
};
-Router.prototype.respond = function(reqPromise) {
- var self = this;
+Router.prototype.respond = function(req) {
+ var self = this
+ , noRouteMatchesReason = 'No route matches request'
+ , route = self.handler(req.method, req.pathInfo);
- return when(reqPromise, function(req) {
- var route = self.handler(req.method, req.pathInfo);
+ if (util.no(route)) {
+ return this.nextApp(req);
+ }
- if (util.no(route)) {
- return null;
- }
+ route.bindRouteParametersToRequest(req);
- route.bindRouteParametersToRequest(req);
+ var allBefores = Q.all(self.beforeCallbacks.map(function(cb) { return cb(req) }));
- var allBefores = Q.all(self.beforeCallbacks.map(function(cb) { return cb(req) }));
+ return when(allBefores)
+ .then(function() {
+ // Executes each of the route handlers provided to the route in sequential order.
+ // Waits for one to finish before starting the next so that chaining is possible.
+ var routeHandlerSequence = stack.apply(stack, route.apps);
- // Executes each of the route handlers provided to the route in sequential order.
- // Waits for one to finish before starting the next so that chaining is possible.
- var routeHandlerSequence = stack.apply(stack, route.apps);
+ return routeHandlerSequence(req)
+ })
+ .then(function(resp) {
+ var allAfters = Q.all(self.afterCallbacks.map(function(cb) { return cb(req); }));
- return when(allBefores)
- .then(function() {
- return routeHandlerSequence(req);
- }, function(err) {
- return util.reject('When executing Bogart route handlers', err);
- })
- .then(function(resp) {
- var allAfters = Q.all(self.afterCallbacks.map(function(cb) { return cb(req); }));
+ return when(allAfters, thenResolve(resp));
+ })
+ .then(function(resp) {
+ if (util.no(resp)) {
+ return self.nextApp(req);
+ }
- return when(allAfters, thenResolve(resp));
- }, function(err) {
- return util.reject('When executing Bogart `after` callbacks', err);
- });
- });
+ return resp;
+ });
};
Router.prototype.show = Router.prototype.get = function(path /*, jsgiApps */) {

0 comments on commit e518294

Please sign in to comment.