【问题标题】:Node JS loop and callbackNode JS 循环和回调
【发布时间】:2017-02-06 13:58:40
【问题描述】:

我正在使用node-rest-client 对端点进行 GET 调用,并希望多次(在循环中)进行此调用,然后公开响应的参数。
代码如下:

// registering remote methods
client.registerMethod("reflect", "<the URL>", "GET");
// call the method
var i = 10;
while (i>0) {
    client.methods.reflect(function (data, response) {
        console.log("x-forwarded-for: " + data.headers["x-forwarded-for"]);
        // raw response
        //console.log(response);
      });
    i--;
}

我得到的错误是:

TypeError: Cannot read property 'x-forwarded-for' of undefined

如果i 等于 2,则可以。 我想问题出在这样一个事实,即这是异步执行,并且同时触发所有调用,导致沿线某处出现一些阻塞。

同步执行的最佳方式是什么(假设这是问题所在)?

【问题讨论】:

标签: node.js loops asynchronous node-rest-client


【解决方案1】:

首先请检查 x-forwarded-for 响应中的谎言,如果同样的问题仍然存在(异步调用),那么 只需将此调用包装在这样的匿名函数中

while(i > 0) {
    (function abc(){
        client.methods.reflect(function (data, response) {
            console.log("x-forwarded-for: " + data.headers["x-forwarded-for"]);
            // raw response
            //console.log(response);
        });
    }())

    i--;
}

【讨论】:

  • 包装没有意义。内部回调函数 i 变量未使用。
  • 然后把这个i变量去掉就好了,没关系
猜你喜欢
  • 2018-06-29
  • 2016-09-07
  • 1970-01-01
  • 2014-05-05
  • 2021-11-22
  • 2019-11-06
  • 1970-01-01
  • 1970-01-01
  • 2021-07-30
相关资源
最近更新 更多