gpt4 book ai didi

javascript - 循环内的 Node.js 回调具有错误的迭代器值

转载 作者:行者123 更新时间:2023-12-02 14:48:32 24 4
gpt4 key购买 nike

for(var i in companyTickerList) {
console.log('i = ' + i);
//construct url
var url = base_url + companyTickerList[i];
console.log('url = ' + url);
request(url, function(error, response, xml) {
if(!error && response.statusCode == 200) {
//load xml returned from GET to url
var cik_xml = cheerio.load(xml)
console.log('i = ' + i);
//map company ticker symbol to cik value scraped from xml
TickerToCIK[companyTickerList[i]] = cik_xml('company-info cik').text();
console.log('TICKER = ' + companyTickerList[i] + ' CIK = ' + cik_xml('company-info cik').text());
}

}

//CONSOLE LOG OUTPUT
i = 0
http://www.sec.gov/cgi-bin/browse..........SNPS
i = 1
http://www.sec.gov/cgi-bin/browse..........IBM
i = 2
http://www.sec.gov/cgi-bin/browse..........BA
i = 3
http://www.sec.gov/cgi-bin/browse..........GM
i = 4
http://www.sec.gov/cgi-bin/browse..........F
i = 5
http://www.sec.gov/cgi-bin/browse..........C
i = 6
http://www.sec.gov/cgi-bin/browse..........CVX

i = 6
TICKER = CVX CIK = 0000883241
i = 6
TICKER = CVX CIK = 0000037996
i = 6
TICKER = CVX CIK = 0000831001
i = 6
TICKER = CVX CIK = 0000093410
i = 6
TICKER = CVX CIK = 0001467858
i = 6
TICKER = CVX CIK = 0000012927
i = 6
TICKER = CVX CIK = 0000051143

为什么每次请求调用触发后,回调函数中的迭代器值 i 总是等于 6?它使我的 TickerToCIK map 的键始终为 CVX。我需要将 i 作为参数传递给回调函数吗?

最佳答案

var 很棘手:)JavaScript 实际上是这样评估你的代码的:

var i;
for(i in companyTickerList) {
console.log('i = ' + i);
// ...

意思是,它就像在第一行代码之前执行的 var 定义。

因此,您实际上有一个变量 i,它会更新 6 次,最终 i = 6

您的 request() 回调是异步,当您的第一个回调实际被调用时,循环早已消失,i等于 6。

解决方案:

一种可能的解决方案是使用IIFE(立即调用函数表达式)。

即:

    (function (i) {
// async code using i
})(i);

像这样:

for (var i in companyTickerList) {
console.log('i = ' + i);
//construct url
var url = base_url + companyTickerList[i];
console.log('url = ' + url);

(function (i) {

request(url, function (error, response, xml) {
if (!error && response.statusCode == 200) {
//load xml returned from GET to url
var cik_xml = cheerio.load(xml);
console.log('i = ' + i);
//map company ticker symbol to cik value scraped from xml
TickerToCIK[companyTickerList[i]] = cik_xml('company-info cik').text();
console.log('TICKER = ' + companyTickerList[i] + ' CIK = ' + cik_xml('company-info cik').text());
}
});

})(i);
}

关于javascript - 循环内的 Node.js 回调具有错误的迭代器值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36389324/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com