gpt4 book ai didi

javascript - #9 挑战 - 了解您的 Node (异步回调)

转载 作者:太空宇宙 更新时间:2023-11-04 00:37:07 24 4
gpt4 key购买 nike

我正在努力应对这个特殊的挑战:

练习 9 - 杂耍异步

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 bl = require('bl')
var results = [];
var count = 0

function getURLs() {
var urls = []
for(var i = 2; i < process.argv.length; i++){
urls.push(process.argv[i]);
}
return urls
}

function getHTTP(url){
http.get(url, function(response){
response.pipe(bl(function(err,data){
if(err){return console.error(err)}
results[count] = data.toString();
count ++;
if (count === process.argv.length - 2){
printAll()
}
}))
})
}

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

function start(){
retrivedURL = getURLs()
for(var i = 0; i < retrivedURL.length; i++){
getHTTP(retrivedURL[i])
}
}

start()

我似乎不知道哪里出了问题——它是按照检索到的 URL 的顺序输出的。

最佳答案

您可以使用 async.eachSeries 来实现此目的,即使此 URL 调用异步。解释得很好here

关于javascript - #9 挑战 - 了解您的 Node (异步回调),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38532785/

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