title: Using Q promises in HTTP requests with NodeJs
body: <p>I'm trying to make a chain of promises functions which use HTTP requests in NodeJS with Kraken framework.</p>
  
  <p>My code could work in 90% of cases, but if the distant requested server takes time to respond, the code will return an error with undefined values. So I think Q is a good solution to prevent that.</p>
  
  <p>Here's the situation : </p>
  
  <p>We access to a URL with a "code" parameter -> the route controller takes this param to use it in a HTTP POST request -> the response (a token) is stored in a variable and used in an other HTTP GET request -> the response (multiple JSON objects) is stored in variable too -> all variables are stored in a MongoDB. 
  If functions are not used in this order, of course it fails.</p>
  
  <pre><code>var Q = require('q');
  
  module.exports = function (router) {
    router.get('/', function (req, res) {
      var codein = req.param('code');
      if(codein){
          console.log('Provided code: ' + codein+'\n');
          getAccessToken(codein).then(function(token){
              console.log('Provided AccessToken: ' + token + '\n');
              getUsername(token).then(function(userdata){
                  console.log('Provided Username: ' + JSON.parse(userdata).username + '\n');
                  storeData(userdata).then(function(msg){
                      console.log(msg);
                      res.redirect('/dashboard/' + JSON.parse(userdata).username);
                  });
              });
          });
  
      }
      else{
          console.log('Access Denied, redirecting...');
          res.redirect('/');
      }
    });
  };
  </code></pre>
  
  <p>This method works, but actually didn't resolve the problem, because sometimes variable are undefined again. I think it's my request functions which aren't well made...</p>
  
  <p>Here's an example of the first function with POST request :</p>
  
  <pre><code>var getAccessToken = function(cod){
      var def = Q.defer();
      var data = querystring.stringify({
              client_id:"1234567890", 
              client_secret:"******", 
              grant_type:"authorization_code", 
              redirect_uri:"http://localhost:8000/r/callback", 
              code:cod
      });
  
      var options = {
          host: 'domain.server.com',
          port: 443,
          path: '/api/oauth2/token',
          method: 'POST',
          headers: {
              'Content-Type': 'application/x-www-form-urlencoded',
              'Content-Length': Buffer.byteLength(data)
          }
      };
  
      var response = "";
  
      var req = https.request(options, function(res) {
          res.setEncoding('utf8');
          res.on('data', function (chunk) {
              response += chunk;
          });
  
          res.on('end', function(){
              var json = JSON.parse(response);
              var acto = json.access_token;
              def.resolve(acto);
  
          });
      });
  
      req.write(data);
      req.end();
      return def.promise;
  
  };
  </code></pre>
  
  <p>In this case the acto variable can be undefined... So am I using Q in a wrong way ? </p>
  
  <p><strong><em>EDIT</em></strong></p>
  
  <p>To understand my problem, let me show you what can I have in my output console (really rare but happens) :</p>
  
  <pre><code>Provided code: 12345678910
  
  Provided Username: user543210
  </code></pre>
  
  <p>Instead of :</p>
  
  <pre><code>Provided code: 12345678910
  
  Provided AccessToken: 9876543210
  
  Provided Username: user
  </code></pre>