在将日志logging到数组中的控制台之前,检查URL是否存在

我正在编写一个用于生成站点地图的节点应用程序,并且遇到了我需要的特定部分的问题(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]的值传递给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闭包 – 简单的实例

或者,如果您使用的是支持它的解释器,则可以在for语句中使用let关键字。

 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 (let 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 {} })} });