LearnYouNode-杂耍异步(#9)-我必须缺少一些东西 [英] LearnYouNode - Jugglling Async (#9) - I Must be Missing Something

查看:66
本文介绍了LearnYouNode-杂耍异步(#9)-我必须缺少一些东西的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

There seem to be many questions about this problem out here, but none directly relate to my question AFAICT. Here is the problem statement:


此问题与先前的问题(HTTP COLLECT)相同,因为您需要使用http.get ()。但是,这一次您将获得三个URL作为前三个命令行参数。

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.

您必须收集每个URL提供给您的完整内容,并且将其打印到控制台(stdout)。您无需打印出长度,只需将数据打印为字符串即可;每个网址一行。要注意的是,您必须按照与作为命令行参数提供给您的URL相同的顺序打印它们。

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.

此处是我最初的解决方案失败了:

Here is my original solution that fails:

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)
})

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

This is the solution they recommend:

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 程序的范围之外尝试解决方案时,它似乎可以正常工作。但是我知道那可能意义不大...。所以,一个比我更了解节点的人...在乎解释我哪里出了问题? TIA。

What I fail to grok is the fundamental difference between my code and the official solution. I am doing the same as their solution when it comes to stuffing the replies into an array to reference later. 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? When I try my solution outside the bounds of the learnyounode program it seems to work just fine. But I know that probably means little.... So someone who knows node better than I... care to explain where I have gone wrong? 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 取决于数组中的最高索引,而不是分配的元素的实际数量。

Yes, it does matter. The .length of an array depends on the highest index in the array, not the actual number of assigned elements.

仅当异步请求的结果无序。如果您首先分配索引 0 ,然后分配 1 ,然后分配 2 依此类推, .length 与分配的元素数匹配,并且与其 count er相同。但现在尝试一下:

The difference surfaces only when the results from the asynchronous requests come back out of order. If you first assign index 0, then 1, then 2 and so on, the .length matches the number of assigned elements and would be the same as their counter. But now try out this:

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 都输出数组,它将打印

If you would test the length after each assignment and output the array whenever you get 4, it would print

"Hello ld!"
"Hello World!"

这篇关于LearnYouNode-杂耍异步(#9)-我必须缺少一些东西的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆