iQ.
iQ.

Reputation: 3953

ExpressJS will the callback chain execute if res returns early?

A simple question, if I have a route setup with a chain of callbacks e.g.

app.route('/myroute').post(callback1, callback2, callback3);

I call next() on each of my callback, except the last one.

Suppose I use my 'res' object to render and send back a response on callback2 but I still want to do some processing on callback3 which does not need to interact with the client or return anything.

Will my callback3 be always executed even if callback1 or callback2 uses the res object to return a response?

Doing some tests shows that it does call callback3 but some say expressjs will terminate the call chain if res returns a response. So I don't want to have any doubts, is there a clear answer on the behaviour here?

Upvotes: 1

Views: 222

Answers (1)

Julian H. Lam
Julian H. Lam

Reputation: 26134

If you are calling next() in callback2, then the code in callback3 will be executed. The only thing that has "finished" in callback2 is the HTTP request. The connection will be closed, as you've sent a response already. Any further attempts to send a response afterwards will result in: Error: Can't render headers after they are sent to the client.

Upvotes: 1

Related Questions