按顺序在循环中执行请求
execute request in loop in order
我有以下内容:
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);
}
相关文章:
- 防止双击执行两次jQuery post请求
- 暂停函数执行流程,直到ajax请求完成
- Chrome浏览器“;挂起”;同时在循环中执行AJAX请求
- 如何仅在完成对gap.client.youtube的请求.execute后执行函数
- AJAX 请求不会在 400 个错误查询上执行失败
- 嵌套在 .get 请求中的 jQuery 不会执行
- 通过 ajax 请求执行 ajax 请求
- 如何在执行 Ajax 请求大量数据库更新时实现进度条
- 从 Web Worker 执行 AJAX 请求是否可行
- 在不执行ajax请求的情况下,使用jQuery读取HTTP标头以检查404
- Angular在不触发摘要的情况下执行XHR请求
- 按顺序执行ajax请求的动态编号
- 根据条件线性执行请求
- Firefox SDK 多次执行请求
- 如何将 Google 地方自动完成功能配置为仅在输入字段中至少有 n 个字母时执行请求
- 执行请求数组失败,并多次调用Error: done().映射请求数组不会触发请求
- HTTP403: FORBIDDEN——服务器理解请求,但拒绝执行请求
- 使用AngularJS'执行请求的顺序;s ng资源
- 按顺序在循环中执行请求
- 表单没有'不能正确执行请求后功能