gpt4 book ai didi

javascript - 如何让 learnyounode #9 杂耍异步工作

转载 作者:行者123 更新时间:2023-11-30 16:22:13 27 4
gpt4 key购买 nike

我正在尝试学习 nodeschool 的 learnyounode。

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 bl = require('bl');
var http = require('http');

var urls = [process.argv[2], process.argv[3], process.argv[4]]
var dataArray = [];
var count = 0;


for (var i = 0; i <= urls.length-1; i++) {
http.get(urls[i], function(response){
response.setEncoding('utf8').pipe(bl(function (err, data) {
dataArray[i] = data.toString();
count++;
if (count==2){
dataArray.forEach(function(item){
console.log(item);
})
}
}));
});

};

当我尝试验证它时:

  1. 实际:“她会像牛奶吧一样完美地成为妇科伴侣。给我们拿来牙胶,它也像战士一样疯狂。”
  2. 预期:“让我们来点帕尔玛干酪来注意 pav。她会是正确的平板不用担心他有一个巨大的 cookies 。让我们来点 gobful flamin 她会是正确的丁字裤。”

  3. 实际:“”

  4. 预期:“让一只狗起来,它会生病的。他有一个巨大的 Yobbo,像 bonza 一样发脾气。”

  5. 实际:

  6. 预期:“她会像牛奶吧一样成为正确的妇科伴侣。给我们拿一个也像战士一样疯狂的牙胶。”

  7. 实际:

  8. 预计:“”

我在这里做错了什么?

最佳答案

你想检查 count == 3 因为你有 3 个 url。

此外,您也不想在这样的循环中使用函数。在这种情况下,每次执行匿名函数时 i 的值都是 3 ...这就是为什么您只输出第三个 url 的预期值。

这是一个很好的例子:JavaScript closure inside loops – simple practical example

通过将函数包装在一个新函数中,您可以确保 i 正是您想要的。

这应该有效:

var bl = require('bl');
var http = require('http');

var urls = [process.argv[2], process.argv[3], process.argv[4]];
var dataArray = [];
var count = 0;


function juggle (i) {
http.get(urls[i], function(response) {
response.setEncoding('utf8').pipe(bl(function(err, data) {
dataArray[i] = data.toString();
count++;
if (count == 3) {
dataArray.forEach(function(item) {
console.log(item);
});
}
}));
});
}

for (var i = 0; i < 3; i++) {
juggle(i)
}

关于javascript - 如何让 learnyounode #9 杂耍异步工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34573171/

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