title: Returning a response immediately with res.json
body: <p>I have an express route which takes in some parameters, queries the database, and then returns some response.</p>
  
  <p>I am using sequelize to query the db:</p>
  
  <pre><code>router.get('/query', function(req,res) {
      var name = req.params.name;
      var gid = req.params.gid;
  
      // Query the db
      models.user.find({ where: { name: name }}).then(function(user) {
          models.group.find({ where: { id: gid }}).then(function(group) {
              // if user found, return data to client
              if (user) {
                  res.json({"user": user, "group": group});
              }
          });
      }).catch(function(error) {
          // catch any errors from db query
          res.status(500).json({"error":error});
      }); 
  
  
      // Return a server error for any other reason
      // This causes ERROR
      res.status(500).json({"error":"Something went wrong. Check your input."});    
  });
  </code></pre>
  
  <p>But I keep getting the error on the last line:</p>
  
  <pre><code>Can't set headers after they are sent
  </code></pre>
  
  <p>It seems like the last line is ALWAYS run, even if it finds a user (which should return data to the client and be done). </p>
  
  <p>Why doesn't <code>res.json(..)</code> immediately return to the client when a user is found? Since headers were already set, when the last line runs, it throws that error.</p>