Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

refactor respond function to be more readable

  • Loading branch information...
commit e18dceb3bf3438c8ca6808f14075f7173d34fb0a 1 parent b2750fe
@nrstott authored
Showing with 27 additions and 22 deletions.
  1. +16 −21 lib/router.js
  2. +11 −1 lib/util.js
View
37 lib/router.js
@@ -189,30 +189,25 @@ Router.prototype.respond = function(reqPromise) {
route.bindRouteParametersToRequest(req);
- /* Invoke all 'before' functions and save any promises. */
- var promiseArray = [];
- self.beforeCallbacks.forEach(function(cb) {
- promiseArray.push(cb.call(self, req));
- });
+ var allBefores = Q.all(self.beforeCallbacks.map(function(cb) { return cb(req) }));
+
+ // 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);
- /* Wait until any promises have completed. */
- return when(Q.all(promiseArray), function() {
- return Q.whenCall(function() {
- var jsgiApp = stack.apply(stack, route.apps);
- return jsgiApp(req);
- }, function(resp) {
- /* Invoke all 'after' functions and save any promises. */
- var promiseArray = [];
- self.afterCallbacks.forEach(function(cb) {
- promiseArray.push(cb.call(self, req));
- });
-
- return when(Q.all(promiseArray), thenResolve(resp));
+ return when(allBefores)
+ .then(function() {
+ return routeHandlerSequence(req);
}, function(err) {
- // work around for issue in whenCall, it tries to call rejectCallback even if one is not provided
- throw 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));
+ }, function(err) {
+ return util.reject('When executing Bogart `after` callbacks', err);
});
- });
});
};
View
12 lib/util.js
@@ -1,3 +1,5 @@
+var q = require('promised-io/promise');
+
exports.no = function(value) {
return value === undefined || value === null;
};
@@ -82,4 +84,12 @@ exports.ensureSetCookieArray = function(response) {
}
return response;
-};
+};
+
+exports.reject = function(reason) {
+ var deferred = q.defer();
+
+ deferred.reject(reason);
+
+ return deferred.promise;
+}
Please sign in to comment.
Something went wrong with that request. Please try again.