nodeschool.io 9

~~ JUGGLING ASYNC ~~

其实就是一个循环,在循环里面输出的顺序,和排列后在外面的顺序不一样,这是为什么呢?

用第三方async包,直接报错了……

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.

----------------------------------------------------------------------
HINTS:

Don't expect these three servers to play nicely! They are not going to
give you complete responses in the order you hope, so you can't
naively just print the output as you get it because they will be out
of order.

You will need to queue the results and keep track of how many of the
URLs have returned their entire contents. Only once you have them all,
you can print the data to the console.

Counting callbacks is one of the fundamental ways of managing async in
Node. Rather than doing it yourself, you may find it more convenient
to rely on a third-party library such as http://npm.im/async or
http://npm.im/after. But for this exercise, try and do it without any
external helper library.

----------------------------------------------------------------------

jugglingAsync.js

var bl = require("bl"),
    http = require('http'),
    count = 0,
    result = [];

function printSult(){
    for(var i = 0 ; i < 3 ; i++){
        console.log(result[i]);
    }
}

function httpGet(index){
    http.get(process.argv[2 + index], function(res) {
    res.pipe(bl(function(err,data){
        if(err) console.log(err);
        result[index] = data.toString();
        count ++ ;
        if(count == 3){
            printSult();
        }
    }));
});
}

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

 

转载于:https://www.cnblogs.com/della/p/3433867.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值