gpt4 book ai didi

javascript - learnyounode - 异步杂耍 - http.get() 的重复结果

转载 作者:行者123 更新时间:2023-11-29 21:49:38 25 4
gpt4 key购买 nike

在learnyounode上做教程,遇到如下问题。来自描述:

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.

似乎有时我会得到所提供的其中一个 url 的重复结果,但是,有时代码会通过教程作者创建的测试...

http = require('http')

var urls = process.argv.slice(2)

var output = []

// allocate space for the contents of each response.
output.length = urls.length

var counter = 0

urls.forEach( function(url, index, array) {

http.get(url, function (response) {

stream = ''

response.on("error", function (error) {
console.error('There was an error:', err)
})

response.on("data", function (data) {
stream = stream + data.toString();
})

response.on("end", function () {
// it seems that this even fires multiple times for the same url (?)
output.splice(index, 1, stream);

counter += 1;

if (counter == array.length) {
output.forEach( function (element, index, array) {
console.log(element);

})
}
})
})
})

最佳答案

由于未能使用 var 初始化 stream,您已将其设为全局变量。这意味着每个请求都试图初始化为 '',然后在同一个变量中累积数据。根据返回响应和触发事件的顺序,您将得到各种无意义的输出。

关于javascript - learnyounode - 异步杂耍 - http.get() 的重复结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29929439/

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