title: making http call in nodejs in chain
body: <p>how to make http call api in a chain</p>
  
  <p>my requirement is create account</p>
  
  <p>i have to following events </p>
  
  <p>1 check the account is exist or not 
    2 if account is not exists means i have create account </p>
  
  <p>for account exists or not 
   i wrote one function search (account name is unique ) </p>
  
  <pre><code> Account.search({"name":"username"})
  </code></pre>
  
  <p>it retrieve the account name with "username"
    if it not found  i am calling Account.save()</p>
  
  <p>Account.da.js</p>
  
  <pre><code>exports.search = function (query) {
  
      var deferred = Q.defer();
      request({
          url: config.ctxDa.url + "/account/search",
          method: "GET",
          qs: query,
          useQuerystring: true,
          headers: {"Content Type": "application/json"}
      }, function (error, response, body) {
  
  
          if (!error &amp;&amp; response.statusCode == 200) {
              deferred.resolve(body);
          }
          else {
              deferred.reject(error);
  
          }
  
      });
  
      return deferred.promise;
  
  };
  </code></pre>
  
  <p>// for creating account </p>
  
  <pre><code>  exports.save = function (newAccount) {
          var deferred = Q.defer();
  
  
          request({
              url: config.ctxDa.url + "/account",
              method: "POST",
              headers: {"Content Type": "application/json"},
              json: newAccount
  
          }, function (error, response, body) {
  
              if (!error &amp;&amp; response.statusCode == 200) {
                  deferred.resolve(body);
              }
              else {
                  deferred.reject(error);
  
              }
  
          });
  
          return deferred.promise;
  
      };
  </code></pre>
  
  <p>this is my utility function to create account </p>
  
  <pre><code>exports.createAccount = function (account) {
  
      var deferred = Q.defer();
  
  
      Account.search({name: account.name}).then(function (body) {
  
          if (JSON.parse(body).length == 0)
              return;
  
             return throw  new Error("account already exists");
  
      }).then(function () {
  
          return Account.save(account).then(function (body) {
  
              return deferred.resolve(body);
          }, function (error) {
  
              throw  error;
  
          })
  
  
      }).catch(function (error) {
  
          deferred.reject(error);
  
      })
      .done();
  
  
  return deferred.promise;
  
  
  }
  </code></pre>
  
  <p>what is best practice to call http calls in chain order</p>