0

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:

  • Once a token has been obtained (from asyncRefreshToken), use the request package to query the Google Analytics API for a list of brands.

  • The brands are in an array brandsConfig.brands[k], the corresponding title can be obtained from brandsConfig.brands[k].title

  • The result for now, during the time I'm trying to learn can just be in the console.

  • So ideal result:

    * Got the token! 1234567890
    * Brand 1 : 582432
    * Brand 2 : 523423
    
  • Current output:

    * Got the token! 1234567890
    * Brand 2 : 582432
    * Brand 2 : 523423
    
turtlepower
  • 708
  • 1
  • 7
  • 18
  • 1
    Which parameter are you talking about? Please be more specific. See [ask] for guidance about how to ask question. So far your question isn't much better than "something doesn't work, how can I make it work". – Felix Kling May 24 '16 at 22:09
  • You've got an async operation inside a `for` loop inside a `.then()` handler. You then declare a couple variables inside the `request()` callback, but then never do anything with them. This looks like several things wrong. For us to help you, we need to know more about what you're trying to accomplish and what problem you're having with the current code. FYI, ***pass through a simple parameter*** is not a well defined phrase and does not tell us what you're trying to accomplish or what problem you are having with your current implementation. – jfriend00 May 24 '16 at 22:11
  • @tony You probably want to start by URL encoding your parameters (`encodeURIComponent(x)`) – Tibrogargan May 24 '16 at 22:11
  • Regarding your edit, see [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/q/750486/218196) – Felix Kling May 24 '16 at 22:12

1 Answers1

1

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).

Russbear
  • 1,261
  • 1
  • 11
  • 22
  • Thanks! Exactly what I'm after. Very straight forward, step-by-step description of what my loop is doing and shouldn't be doing. Will obviously need to read up now. – turtlepower May 24 '16 at 22:46