gpt4 book ai didi

javascript - Node.js 中的异步 http.get 调用(学习 Node 练习)

转载 作者:搜寻专家 更新时间:2023-11-01 00:29:19 24 4
gpt4 key购买 nike

我正在通过做 learnyounode exercises from nodeschool 来学习 Node .在第 8 个练习中,他们要求编写一个执行以下操作的程序:

  • 将三个 URL 作为参数,
  • 从回复中收集数据,
  • 按照与参数相同的顺序将它们打印到控制台。

他们简要提到了异步库的存在,这有助于计算回调,但他们也邀请在没有它​​们的情况下完成练习。我最初的解决方案如下:

var http = require('http'); 
var bl = require('bl');
var results = Array();
var count = 0;

function printResults() {
for (var i = 0; i < 3; i++) {
console.log(results[i]);
}
}


for (var index = 0; index < 3; index++)
http.get(process.argv[2+index], function(response) {
response.pipe(bl(function(err,data){
if(err) console.error(err)
results[index] = data.toString();
count++;

if(count==3) printResults(results);
}));
});
}

然而,出于某种原因,这打印了三次“undefined”。我碰巧找到了正确的解决方案,只需用一个函数替换 for 循环并将该函数的调用包含在另一个 for 循环中。

(...)


function httpGet (index) {
http.get(process.argv[2+index], function(response) {
response.pipe(bl(function(err,data){
if(err) console.error(err)
results[index] = data.toString();
count++;

if(count==3) printResults(results);
}));
});
}

for (var i = 0; i < 3; i++)
httpGet(i)

但是,我不明白这种差异究竟是如何使解决方案起作用的。谁能赐教一下?

最佳答案

在您的代码中,您将引用传递给您迭代的变量,因此在调用回调时它等于 3。请参见以下示例:

编辑:我忘了总结一下,你的代码不会工作,因为回调将所有结果设置为结果数组的索引 3,而你正在打印从 0 到 2 的索引

for(var index = 0; index < 3; index++){
setTimeout(function(){
console.log(index);
}, 500);
}

通过从中创建函数,您将添加更多范围:

function fun(index){
setTimeout(function(){
console.log(index);
}, 500);
}

for(var index = 0; index < 3; index++){
fun(index);
}

你仍然可以使用匿名函数,但你需要用这样的作用域包围它:

for(var index = 0; index < 3; index++){
setTimeout((function(index){
return function(){
console.log(index);
}
})(index), 500);
}

为了让它更清楚一点,我将在不同的范围内使用不同的变量名:

for(var outerIndexVariable = 0; outerIndexVariable < 3; outerIndexVariable++){
setTimeout((function(innerIndexVariable){
return function(){
console.log(innerIndexVariable);
}
})(outerIndexVariable), 500);
}

关于javascript - Node.js 中的异步 http.get 调用(学习 Node 练习),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43577849/

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