Skip to content

Instantly share code, notes, and snippets.

@mhofwell
Last active November 7, 2020 23:56
Show Gist options
  • Save mhofwell/7b8736199a8326f3d11e0945bc784d4a to your computer and use it in GitHub Desktop.
Save mhofwell/7b8736199a8326f3d11e0945bc784d4a to your computer and use it in GitHub Desktop.
Async Request Handling in Node with Counting Callbacks
// this node program takes 3 URLs provided by the first 3 command line arguments and gets some data from those URLS.
// the program then prints each set of data in the order it was called.
// counting callbacks was a requirement as a method to handle the asyncronicity.
const http = require('http');
const urls = [];
const dataArr = [];
let count = 0;
// create the URL array
for (let i = 2; i < process.argv.length; i++) {
urls.push(process.argv[i]);
}
function httpGet(index) {
// variable declaration every call to empty the string.
let chunk = '';
// send a get request to each url in the array and wait for a response.
http.get(urls[index], response => {
response.on('error', console.error);
// set the response object to recieve as a string with utf8 encoding.
response.setEncoding('utf8').on('data', data => {
// concatenate the incoming string into a variable.
chunk += data.concat('');
});
// when the URL response is done, then add the string into the array, in order.
response.on('end', () => {
count += 1;
dataArr[index] = chunk;
// if 3 callbacks have fininshed then loop over the array and log each item.
if (count === 3) {
for (let i = 0; i < dataArr.length; i += 1) {
console.log(dataArr[i]);
}
}
});
}).on('error', console.error);
}
// call the function for the number of URLs provided in the process.argv array.
for (let i = 0; i < urls.length; i++) {
httpGet(i);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment