Why can I execute code after “res.send”?

前端 未结 2 959
暗喜
暗喜 2020-11-28 23:50

I\'m wondering what the mechanics behind the behaviour of the following code are:

res.send(200, { data: \'test data\' });
console.log(\'still here...\');
         


        
2条回答
  •  心在旅途
    2020-11-29 00:21

    Edit: I no longer do what is explained below, as you shouldn't return a value when there is no need for it. It makes your code less readable and looks hackish. Instead, I suggest separating the return statement from the res.send(). @slavafomin explained this well in the comments.

    A simple way to stop the execution of the function and send a response at the same time is by doing

    return res.send('500', 'Error message here');
    

    This allows you to use short if statements to handle errors such as:

    if (err) {
        return res.send('500', 'Error message here');
    }
    

    The exact return of the res.send function is an object that seems to contain the entire state of the connection after you ended it (request, status, headers, etc.), but this should be unimportant since you won't be doing anything with it.

提交回复
热议问题