我正在使用node-rest-client
对端点进行GET调用,并且希望多次(在循环中)进行此调用,然后公开响应的参数。
代码如下:节点JS循环和回调
// 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中的异步for循环]的副本(http://stackoverflow.com/questions/21184340/async-for-loop-in-node-js) – DrakaSAN
您可以使用控制流库,如'async',或使用递归来做到这一点。承诺也会起作用。 – DrakaSAN
谢谢 - 是的,只是看到了这个我相信解决了这个问题:https://github.com/caolan/async/blob/v1.5.2/README.md#white – Christian68