diff --git a/lib/chain.js b/lib/chain.js index f1fc5caf2..041b6fbf6 100644 --- a/lib/chain.js +++ b/lib/chain.js @@ -221,8 +221,12 @@ function call(handler, err, req, res, _next) { } else if (!hasError && arity < 4) { // request-handling middleware process.nextTick(function nextTick() { - const result = handler(req, res, next); - if (result && typeof result.then === 'function') { + let nextCalled = false; + const result = handler(req, res, (...params) => { + nextCalled = true; + next(...params); + }); + if (!nextCalled && result && typeof result.then === 'function') { result.then(resolve, reject); } }); diff --git a/test/server.test.js b/test/server.test.js index 5fd108061..7abffb7ea 100644 --- a/test/server.test.js +++ b/test/server.test.js @@ -2996,6 +2996,41 @@ test('req and res should use own logger by if set during .first', function(t) { }); }); +test('should not call then when next called', function(t) { + let counter = 0; + SERVER.use(function first(req, res, next) { + next(); + return Promise.resolve(); + }); + + SERVER.get('/ping', function echoId(req, res, next) { + counter++; + t.equal(counter, 1); + next(); + }); + + CLIENT.get('/ping', function() { + t.end(); + }); +}); + +test('should stop after next(false)', function(t) { + let counter = 0; + SERVER.use(function first(req, res, next) { + next(false); + return Promise.resolve(); + }); + + SERVER.get('/ping', function echoId(req, res, next) { + counter++; + next(); + }); + CLIENT.get('/ping', function() { + t.equal(counter, 0); + t.end(); + }); +}); + test('should throw if handleUncaughtExceptions is invalid', function(t) { t.throws(() => { restify.createServer({