raj
raj

Reputation: 817

Multiple requests overwriting variable values

I am fairly new to nodejs and I have a scenario where when a user hits an endpoint, I need to make two post calls. The first API call returns to me a URL that I am supposed to use in my second call. Here is a generic module I had written to do these post calls.

// First call
requester.post(options1).then(function(result1){
    var options2 = {
        url: result1.url,
        req: req,
        res: res
    }
    ...
    // Second Call
    requestor.post(options2).then(function(result2) {
    })
}) 

var requestor = {
  post: function(options) {
    url = options.url;
    ...

    var deferred = q.defer();

    ...
    var post = request.post(url, data, function (error, response, body) {
      if (!error && response.statusCode == 200) {
        try {
          deferred.resolve(body);
        }
        catch(e) {
          deferred.reject(new Error('Request failed while processing request'));
        }
      } else {
        deferred.reject({code: code});
      }
    })
    ...
    return deferred.promise;
  }
}

My problem is that when I have two requests come in at the exact microsecond, the url variable is getting overwritten. While the first request's "Second call" is still in progress (and in my case eventually times out), my second request's second call overwrites the url variable. Please suggest what I should fix/change.

Upvotes: 0

Views: 787

Answers (1)

Praveena
Praveena

Reputation: 6941

It is overwriting url because url is a global variable

var requestor = {
 post: function(options) {
   url = options.url;

Change above code snippet to this

var requestor = {
 post: function(options) {
   var url = options.url;

Upvotes: 1

Related Questions