سؤال

I've been using Restify for some time now. I ran across some code that lacks next() and it occurred to me that I'm not sure if I fully understand the reason why next() should be called after res.send(). I get why would use it in a middleware situation, but for a normal route why is it needed? For example:

server.get('/a/:something/',function(req,res,next) {
    res.send('ok');
});

vs

server.get('/b/:something/',function(req,res,next) {
    res.send('ok');
    return next();
});

If return next(); is left out of the code it seems to not cause errors and works from what that I can see.

هل كانت مفيدة؟

المحلول

The restify API Guide has this to say:

You are responsible for calling next() in order to run the next handler in the chain.

The 'chain' they are referring to is the chain of handlers for each route. In general, each route will be processed by multiple handlers, in a specific order. The last handler in a chain does not really need to call next() -- but it is not safe to assume that a handler will always be the last one. Failure to call all the handlers in a chain can result in either serious or subtle errors when processing requests.

Therefore, as good programming practice, your handlers should always call next() [with the appropriate arguments].

نصائح أخرى

Another issue (currently) is that the Server after event is not emitted if all handlers don't call next. For example, if you are using auditLogger to log requests using the after event, you won't get logs for any requests that reach a handler that doesn't call next.

I have opened a PR to fix the issue so that the after event is emitted either way, but calling next is the expected norm for apps using restify.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top