App.get - is there any difference between res.send vs return res.send

I'm new to node and expressing. I've seen examples of app.get and app.post using both "res.send" and "return res.send". It is the same?

var express = require('express');
var app = express();

app.get('/', function(req, res) {
  res.type('text/plain');
  res.send('i am a beautiful butterfly');
});

      

or

var express = require('express');
var app = express();

app.get('/', function(req, res) {
  res.type('text/plain');
  return res.send('i am a beautiful butterfly');
});

      

+3


source to share


2 answers


The keyword is return

returned from your function, thus ending its execution. This means that any lines of code after it will not be executed.

In some cases, you can use res.send

and then do other things.



app.get('/', function(req, res) {
  res.send('i am a beautiful butterfly');
  console.log("this gets executed");
});

app.get('/', function(req, res) {
  return res.send('i am a beautiful butterfly');
  console.log("this does NOT get executed");
});

      

+3


source


app.get('/', function(req, res) {
    res.type('text/plain');
    if (someTruthyConditinal) {
        return res.send(':)');
    }
    // The execution will never get here
    console.log('Some error might be happening :(');
});

app.get('/', function(req, res) {
    res.type('text/plain');
    if (someTruthyConditinal) {
        res.send(':)');
    }
    // The execution will get here
    console.log('Some error might be happening :(');
});

      



+1


source







All Articles