-
Notifications
You must be signed in to change notification settings - Fork 0
/
juggling_async.js
63 lines (50 loc) · 1.85 KB
/
juggling_async.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
* 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.
----------------------------------------------------------------------
*/
var http = require('http');
var cnt = 3;
var content = [];
var makeRequest = function(host, i) {
http.get(host, function(res) {
res.setEncoding('utf-8');
var body="";
res.on('error', console.error);
res.on('data', function(chunk) {
body+= chunk;
});
res.on('end', function() {
content[i]=body;
cnt--;
if(cnt==0){
for(var c in content){
console.log(content[c]);
}
}
});
});
}
for (var i = 0; i < 3; i++) {
makeRequest(process.argv[i+2], i);
}