title: When and how to return an http response only when a promise is complete?
body: <p>I have the following code</p>
  
  <pre><code>api.stuff_by_id = function (req, res) {
      var collection = collectionName;
      var search = getLuceneSearchString(req.body);
  
      luceneDb.search(collection, search)
          .then(function (result) {
              var result_message = result.body;
              console.log(result_message);
              res.send(result);  // this is the response I'd actually like to see returned.
          })
          .fail(function (err) {
              console.log(err);
              res.send(err);  // or this one if there is an error.
          })
  
      res.send('test');  // however this is the only one that gets returned.
  };
  </code></pre>
  
  <p>I realize that the only response that will show when doing a curl request against this call is the last response, since the others are still processing for a split second. However I actually need to have the res.send(result) or res.send(err) calls give the response instead of the res.send('test'). What is a way to make the server wait to respond with one of the correct responses instead? Is there a way to wait somehow or some other method for doing this?</p>
  
  <p>Thanks!</p>
  
  <p><strong>Solution</strong> <em>(@NotMyself answered below, but helped me get to the following code offline). The solution was fairly easy, albeit not entirely obvious at first.</em></p>
  
  <p>We pulled the abstraction to a better level, where api.stuff_by_id just returned a promise of the promise returned from the luceneDb.search function. Once that got bubbled up to the upper level then that was used, under a .then call of the promise to complete and send the respond (res.send) back up to the client. Here's what the method looked like afterwards.</p>
  
  <p>The function setup for the post looks like this:</p>
  
  <pre><code>app.post('/identity/by',
      passport.authenticate('bearer', { session: false}),
      function (req, res) {
          luceneDb.search(req.body)
              .then(function (result) {
                  res.send(result);
              })
              .fail(function (err) {
                  res.statusCode = 400;
                  res.send(err);
              });
      });
  </code></pre>
  
  <p>and the luceneDb.search function looks like this:</p>
  
  <pre><code>luceneDb.search = function (body) {
      var collection = data_tier.collection_idents;
      var search = getLuceneSearch(body);
  
      if (search === '') {
          throw new Error
          'Invalid search string.';
      }
  
      return orchestrator.search(collection, search)
          .then(function (result) {
              var result_message = result.body;
              console.log(result_message);
              return result.body;
          })
  };
  </code></pre>
  
  <p>Providing less leakage of concerns too.</p>