【发布时间】: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,则可以。
我想问题出在这样一个事实,即这是异步执行,并且同时触发所有调用,导致沿线某处出现一些阻塞。
同步执行的最佳方式是什么(假设这是问题所在)?
【问题讨论】:
-
你可以使用
async这样的控制流库,或者使用递归来做到这一点。 Promise 也会起作用。 -
谢谢 - 是的,刚刚看到这个,我相信它可以解决问题:github.com/caolan/async/blob/v1.5.2/README.md#whilst
标签: node.js loops asynchronous node-rest-client