turtlepower
turtlepower

Reputation: 758

Parameters not being passed through Request in NodeJs

I am trying to make a request with the request package and can't seem to be able to pass through a simple parameter.

Anyone know what would be the best way to pass it through?

asyncRefreshToken()
  .then(function(token){
    console.log('Got the token! ' + token);
    for(var k=0; k<2; k++){
      var url= 'https://www.googleapis.com/analytics/v3/data/realtime?ids=ga:'+brandsConfig.brands[k].profileId+'&metrics=rt%3AactiveUsers&dimensions=rt%3ApagePath&sort=-rt%3AactiveUsers&access_token='+token;
      var options = {
        url: url,
        method: 'GET'
      }
      request(options, function (error, response, body) {
        if (!error && response.statusCode == 200) {
          // Print out the response body
          var parsed = JSON.parse(body);
          var activeUsers = parsed.totalResults;
          console.log(brandsConfig.brands[k].title + ': ' + activeUsers);
        }
      })
    }
  })

Sorry, I should be more specific - brandsConfig.brands[k].title will only return the last value i.e. brandsConfig.brands[1].title

What I am trying to achieve:

Upvotes: 0

Views: 218

Answers (1)

Russbear
Russbear

Reputation: 1261

Your problem is caused by the combination of a for loop and an asynchronous request. What's happening is that your loop begins, and kicks off the first request. The request is asynchronous (since it's over ye olde interwebs). This means that the code in the callback will not be executed right away, it will be "skipped" until the asynchronous request returns. The important thing is that your for loop keeps executing, incrementing k, and kicking of a new request. Now your code has finished except for the callbacks to the two requests.

Now the first one comes back. It executes the code in the callback. What is the value of k? Well since the loop kept going, the value is now 1. Same thing happens to the second request, k is still 1.

The important thing is that a callback does not create it's own context that only it can touch.

There are 3 ways out of this: figure out a way that does not put an async operation in the for loop, use the async library, or learn about closures (read 3 different explanations to get a good intuition on this one).

Upvotes: 1

Related Questions