按顺序执行循环请求

时间:2014-07-04 16:02:18

标签: javascript node.js

我有以下内容:

var request = require('request')
var j = request.jar()
var url1 = "www.google.com"
var url2 = "www.google.com/images"
request({url: url1,jar: j}, function() {
...
 for (var i = 0; i < list.length; i++) {
// list is just an item from a json response. 
// I need map the list[i] with the body into a JSON object. 
// But if I move the this to the request it get the last item and not each. 
console.log(list[i])
request({url: url2,jar: j}, function(err, response, body) {
          // This print after all the list[i] has printed 
          body = JSON.parse(body)
          console.log(body);
        });
}
});

我希望JSON数组类似于

[{a: list[i], b: body}, {a: list[i], b: body}]

代码评论中的问题。我不是javascript / node。我可能不理解事情是如何运作的。

1 个答案:

答案 0 :(得分:0)

您可以使用闭包来捕获i的值,以便在回调中保留它:

for (var i = 0; i < list.length; i++)
{
    (function(i) {

       request({ url: url2, jar: j }, function(err, response, body) {
           console.log(list[i]);
           body = JSON.parse(body);
           console.log(body);
       });

    })(i);
}