gpt4 book ai didi

javascript - LearnYouNode - 杂耍异步 (#9) - 我一定是错过了一些东西

转载 作者:行者123 更新时间:2023-11-28 05:27:20 25 4
gpt4 key购买 nike

这里似乎有很多关于这个问题的问题,但没有一个与我的问题 AFAICT 直接相关。以下是问题陈述:

This problem is the same as the previous problem (HTTP COLLECT) in that you need to use http.get(). However, this time you will be provided with three URLs as the first three command-line arguments.

You must collect the complete content provided to you by each of the URLs and print it to the console (stdout). You don't need to print out the length, just the data as a String; one line per URL. The catch is that you must print them out in the same order as the URLs are provided to you as command-line arguments.

这是我最初失败的解决方案:

var http = require('http')
var concat = require('concat-stream')

var args = process.argv.slice(2, 5)
var args_len = args.length
var results = []

args.forEach(function(arg, i) {
http.get(arg, function(res) {
res.setEncoding('utf8')
res.pipe(concat(function(str) {
results[i] = str
if (results.length === args_len)
results.forEach(function(val) {
console.log(val)
})
}))
}).on('error', console.error)
})

这是他们推荐的解决方案:

var http = require('http')
var bl = require('bl')
var results = []
var count = 0

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

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

results[index] = data.toString()
count++

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

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

我无法理解的是我的代码和官方解决方案之间的根本区别。当涉及将回复填充到数组中以供稍后引用时,我正在执行与他们的解决方案相同的操作。当我比较两个数组的长度时,他们使用计数器来计算回调的数量(每个数组的长度都会增加);这有关系吗?当我在learnyounode程序范围之外尝试我的解决方案时,它似乎工作得很好。但我知道这可能没什么意义......所以比我更了解 Node 的人......愿意解释我哪里出了问题? TIA。

最佳答案

They use a counter to count the number of callbacks while I am comparing the length of two arrays (one whose length increases every callback); does that matter?

是的,这确实很重要。 .length of an array取决于数组中的最高索引,而不是分配的元素的实际数量。

只有当异步请求返回的结果无序时,差异才会显现出来。如果您首先分配索引 0,然后分配 1,然后分配 2,依此类推,则 .length 与数字匹配分配的元素的数量,并且与其计数器相同。但现在试试这个:

var results = []
console.log(results.length) // 0 - as expected
results[1] = "lo ";
console.log(results.length) // 2 - sic!
results[0] = "Hel";
console.log(results.length) // 2 - didn't change!
results[3] = "ld!";
console.log(results.length) // 4
results[2] = "Wor";
console.log(results.length) // 4

如果您在每次赋值后测试长度并在获得 4 时输出数组,则会打印

"Hello ld!"
"Hello World!"

关于javascript - LearnYouNode - 杂耍异步 (#9) - 我一定是错过了一些东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40032018/

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