title: How to wait until a HTTP request is complete to finish function
body: <p>I've recently started learning javascript, specifically node.js, and am having trouble in the program I am writing.</p>
  <p>Basically I need to make an HTTP request and then set a variable based on the response.</p>
  <p>The problem seems to be when my node.js program sends a response the variable is blank. Here is the code for the HTTP request:</p>
  <pre><code>
  function search(productCategory, productId) {
  
    var options = {
          &quot;method&quot;: &quot;GET&quot;,
          &quot;hostname&quot;: 'HOSTNAME',
          &quot;path&quot;: [
              &quot;PATH&quot;,
          ],
          &quot;headers&quot;: {
              &quot;x-api-key&quot;: &quot;API_KEY&quot;,
  
          }
      };
  
  
      var req =  http.request(options, function (res) {
          var chunks = [];
  
          res.on(&quot;data&quot;, function (chunk) {
              chunks.push(chunk);
          });
  
          res.on(&quot;end&quot;, function () {
  
              var body = Buffer.concat(chunks);
  
  
              var result = JSON.parse(body);
  
             var id = result.result[0].value;
  
              // console.log(id);
              return req.id;
          });
      });
  
       req.end();
  }
  </code></pre>
  <p>console.log correctly outputs the desired value.</p>
  <p>The function that calls this one looks something like this:</p>
  <pre><code>
  
  module.exports = function getId(req, res) {
  
      var categoryId = &quot;&quot;;
      var productId = '';
      var posId = &quot;&quot;;
  
      for(var i=0; i &lt; req.body.result[0].products.length; i++){
  
          categoryId = req.body.result[0].products[i].category_id;
          productId = req.body.result[0].products[i].product_id;
          posId = search(categoryId, productId);
  
          var product = {
              &quot;product number&quot;: i,
              &quot;product_category&quot;: categoryId,
              &quot;product_id&quot;: productId,
              &quot;posId&quot;: posId
          };
  
          productsArray.push(product);
  
  
      }
  
      res.send(JSON.stringify(orderingProducts));
  
  
  };
  
  </code></pre>
  <p>The goal is to send a response with an array of objects with the key posId gotten from the search method.</p>
  <p>Thanks for the help!</p>