title: Define/Use a promise in Express POST route on node.js
body: <p>I currently have a POST route defined in an Express Node.js application as so:</p>
  
  <pre><code>var locationService = require("../app/modules/locationservice.js");
  
  app.post('/createstop', isLoggedIn, function(req, res) {
      locationService.createStop(res, req.body);
  });
  </code></pre>
  
  <p>(for this question, please assume the routing in &amp; db works.. my record is created on form submission, it's the response I am struggling with)</p>
  
  <p>In the <code>locationservice.js</code> class I then currently have</p>
  
  <pre><code>var models  = require('../models');
  
  exports.createStop = function(res, formData) {
  
      models.location.build({ name: formData.name })
                     .save()
                     .then(function(locationObj) {
                               res.json({ dbResult : locationObj });
                           });
  
  };
  </code></pre>
  
  <p>So as you can see, my route invokes the exported function <code>CreateStop</code> which uses the Sequelize persistent layer to insert a record asynchronously, <em>after which</em> I can stick the result on the response in the promised <code>then()</code></p>
  
  <p>So at the moment this only works by passing the response object into the <code>locationservice.js</code> method and then setting <code>res.json</code> in the <code>then()</code> there. This is sub-optimal to me with regards to my service classes, and doesn't feel right either.</p>
  
  <p>What I would like to be able to do is "treat" my <code>createStop</code> method as a promise/with a callback so I can just return the new location object (or an error) and deal with it in the calling method - as future uses of this method might have a response context/parameter to pass in/be populated.</p>
  
  <p>Therefore in the route I would do something more like:</p>
  
  <pre><code>var locationService = require("../app/modules/locationservice.js");
  
  app.post('/createstop', isLoggedIn, function(req, res) {
      locationService.createStop(req.body)
          .then(dataBack) {
              res.json(dataBack); 
          };
  });
  </code></pre>
  
  <p>Which means, I could call <code>createStop</code> from else where in the future and react to the response in <em>that</em> promise handler. But this is currently beyond me. I have done my due diligence research, but some individual expert input on my specific case would be most appreciated.</p>