按顺序在循环中执行请求

execute request in loop in order

本文关键字:执行 请求 循环 顺序      更新时间:2023-09-26

我有以下内容:

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。我可能不明白事情是怎么运作的。

您可以使用闭包捕获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);
}