LearnYouNode:在没有BL / Async / After的情况下玩弄异步

时间:2016-07-20 05:32:02

标签: javascript node.js http asynchronous get

当出现狂野的第9步时,我正在学习本教程。

  

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

     

您必须收集每个网址提供给您的完整内容,然后将其打印到控制台(标准输出)。您不需要打印长度,只需将数据打印为字符串;每个网址一行。问题在于您必须按照与作为命令行参数提供的URL相同的顺序打印它们。

我的代码是(只是在他喜欢的时候它没有工作):

http = require("http");
var url = [process.argv[2], process.argv[3], process.argv[4]];
var responses = [];
var completed_responses = 0;

for(var i in url){
    http.get(url[i], function(response){
        var content = "";
        //if(completed_responses == url.length){
                response.setEncoding("utf-8");
                response.on("data", function(data){
                    content += data;
                })
                response.on("error", console.error);
                response.on("end", function(end){
                    console.log(content);
                });

    })
}

答案是:

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

什么是正确答案没有BL / AFTER / ETC

感谢所有人!

3 个答案:

答案 0 :(得分:0)

当我第一次学习节点时,我自己完成了这个教程,我记得教程的这一步。解决方案相当平庸。无论如何,为了你的答案:

NodeJs Asynchronous programming - Coordinating parallel calls

您可以查看问题中的代码并进行我在答案中建议的修复。这应该解决它没有BL / Async /无论教程提到的其他什么。

答案 1 :(得分:0)

这是我的Juggling Async挑战代码,不使用任何第三方库。

var http = require("http");
var urls = [process.argv[2], process.argv[3], process.argv[4]];

var urlResults = new Array("", "", "");
var allDoneCount = 0;

urls.forEach(function (_url) {

    http.get(_url, function (resp) {
        resp.on("data", function (data) {
            if (_url === urls[0]) {
                urlResults[0] += data.toString();
            } else if (_url === urls[1]) {
                urlResults[1] += data.toString();
            } else {
                urlResults[2] += data.toString();
            }
        })

        resp.on("end", function () {
            allDoneCount++;
            if (allDoneCount === 3) {
                console.log(urlResults[0]);
                console.log(urlResults[1]);
                console.log(urlResults[2]);
            }
        })

        resp.on("error", function (err) {
            console.log(err);
        })

    }).on("error", function (err) {
        console.log(err);
    })
})

答案 2 :(得分:0)

这是无需任何外部模块(http; P除外)的方法。

const http = require('http'); //http module

let results = ["", "", ""]; //this will store the data from http.get()
let counter = 0; //to keep a counter for no of httpget's done

//it will iterate when counter is 3 i.e. the 'end' for all
function print() {
  for (let i = 0; i < 3; i++) {
    console.log(results[i]);
  }
}

//accept index(for process.argv) as parameter
function httpGetter(i) {
  //http.get method on the url first encountered, 2+i because 2 values are reserved
  http.get(process.argv[2 + i], (res) => {
    //for converting (res)ponse to string/alternatively toString() method can be used
    res.setEncoding('utf8');
    //event data on the url, callback with recived chunk as parameter
    res.on('data', function(chunk) {
      //appending the recived chunk to that element of results corresponding to 'i' of httpGetter function
      results[i] += chunk;
    });
    //event end, when no more data is read
    //runs every time for each value of 'i' that is for each url
    res.on('end', function() {
      //to keep count
      counter++;
      //when 3 that is when data from all inputs receved
      if (counter === 3) {
        //print function simply iterating over results array
        print();
      }
    });
  })
}


//inputs are recieved from here
for (let i = 0; i < 3; i++) {
  //i can be index for results
  httpGetter(i);
}