我正在编写一个用于生成站点地图的 Node 应用程序,但在某个特定部分遇到了问题,我需要 (i) 循环遍历包含许多具有特定 URL 键的产品的 JSON 页面,并检查每个产品的 URL 是否存在,以及 (ii) 如果 URL 确实存在,则需要将此 URL 打印到控制台。
var request = require("request");
var url = "http://linktoJSON"
//reads the JSON from the provided URL
request({
url: url,
json: true
}, function (error, response, body) {
//loops through each product on the page
for (i = 0; i < body.length; i++) {
//checks if the URL exists for each product
request('http://www.example.com/product/' + (body[i].urlKey), function (err, response) {
//if the product page does exist
if (response.statusCode === 200) {
//print the product URL
console.log (('<xtml:link\nrel="alternate"\nhreflang="x-default"\nhref="http://www.example.com/' + body[i].urlKey) +'"\n/>');
}
//if the product doesn't exist it does nothing
else
{}
})}
});
这工作得很好,直到它应该打印产品 URL,此时它无法将 [i] 识别为数字,并给我一个错误。是否有其他方法可以将 [i] 的值传递给 console.log 或让它打印与请求所使用的完全相同的链接?
最佳答案
尝试:
var request = require("request");
var url = "http://linktoJSON"
//reads the JSON from the provided URL
request({
url: url,
json: true
}, function (error, response, body) {
//loops through each product on the page
for (i = 0; i < body.length; i++) {
//checks if the URL exists for each product
processKey(body[i].urlKey);
}
});
function processKey(key) {
request('http://www.example.com/product/' + key, function (err, response) {
//if the product page does exist
if (response.statusCode === 200) {
//print the product URL
console.log('<xtml:link\nrel="alternate"\nhreflang="x-default"\nhref="http://www.example.com/' + key +'"\n/>');
}
//if the product doesn't exist it does nothing
else
{
}
});
}
并查看此问题以获取信息: JavaScript closure inside loops – simple practical example
关于arrays - 在将 URL 记录到数组中的控制台之前检查 URL 是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27984375/