简体   繁体   中英

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 ie 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 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM