简体   繁体   English

参数未通过NodeJ中的请求传递

[英]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 抱歉,我应该更具体-brandsConfig.brands [k] .title将仅返回最后一个值,即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. 获取令牌(从asyncRefreshToken)后,请使用请求包在Google Analytics(分析)API中查询品牌列表。

  • The brands are in an array brandsConfig.brands[k], the corresponding title can be obtained from brandsConfig.brands[k].title 品牌位于数组brandsConfig.brands [k]中,可以从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. 您的问题是由for循环和异步请求的组合引起的。 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. 重要的是,您的for循环将继续执行,递增k并执行新请求。 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 ? k的值是多少? Well since the loop kept going, the value is now 1 . 既然循环不断进行,那么现在的值为1 Same thing happens to the second request, k is still 1 . 第二个请求发生了相同的事情, k仍然为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). 有3种方法:找出一种不会在for循环中放置async操作,使用async库或了解闭包的方法(请阅读3种不同的说明以对此有所了解)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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