title: Synchronising the execution of a function as callback parameter in node.js
body: <p>I'm learning js (specifically node&amp;express), and currently struggling to apprehend what exactly is sync and what isn't.</p>
  
  <p>Currently I have let's say A-type sevices that needs to send requests to B-type services.
  I wanted to aggregate these requests in a common function so that all A-type services would use it.</p>
  
  <p>A-type service code (directly in router.post)</p>
  
  <pre><code>var post_data = &lt;some data&gt;
  sendBServicePost(post_data,function (out_data) {
      var resp_data = JSON.parse(out_data);
      if (resp_data.status == "OK") {
        var msg = 'Request OK : '+out_data;
        console.log(msg);
        res.json({ status:"OK", message:msg});
      }
      else
      {
        var msg = 'Login KO: '+out_data;
        console.log(msg);
        res.json({ status:"KO_FUNC", message:msg});
      }
    }).on('error',function (e) {
      var msg = 'Error with call: ' + e.message;
      console.log(msg);
      res.json({ status:"KO_TECH", message:msg});
    });
  </code></pre>
  
  <p>And here's the code of the culprit function :</p>
  
  <pre><code>function sendBServicePost(post_data,callback) {
      var post_options = {
          // Some options
      };
  
      // Sending request
      var post_req = http.request(post_options, function(post_res) {
          post_res.on('data', function(out_data) {
            callback(out_data);
          });
      });
      post_req.write(post_data);
      post_req.end();
  }
  </code></pre>
  
  <p>So, what's happening is I get the error saying I'm trying to add response headers while the response has already been sent, which I assume is happening because the execution of A-type service has finished before the callback function code has been reached
  .
  I thought callbacks were stacked and execution would go through the full stack, so it's hard for me to tell what exactly is async in this chain.</p>
  
  <p>Could someone please shed some light on this matter? How could I synchronize this chain? Some best practices here?</p>