Skip to content

Instantly share code, notes, and snippets.

@lykkin
Created January 4, 2017 23:13
Show Gist options
  • Save lykkin/e7b8bbcfd164c9e27d28f8e6b250b9b2 to your computer and use it in GitHub Desktop.
Save lykkin/e7b8bbcfd164c9e27d28f8e6b250b9b2 to your computer and use it in GitHub Desktop.
var http = require('http')
//Create sample server to send requests to
var server = http.createServer(function(request, response) {
//Grab the last bit of the url and call it the name
var name = request.url.split('/').slice(-1)
//Wait a second to respond
setTimeout(function (){
//Tell the person hello!
response.write('hello ' + name)
response.end()
}, 1000)
}).listen(3500)
var names = [
'alice',
'bob',
'eve'
]
function makeRequest(name, callback) {
var req = http.request({
port: 3500,
host: 'localhost',
path: '/' + name,
method: 'GET'
}, function onResponse(res) {
if (res.statusCode !== 200) {
return callback(res.statusCode, null)
}
res.setEncoding('utf8')
res.on('data', function(data) {
callback(res.statusCode, data)
})
})
req.on('error', function(err) {
console.log('the request errored: ', err)
})
req.end()
}
function requestNames(callback) {
if (names.length === 0) {
//After we run out of people to say hi to, callback to the code that called us
return callback()
}
//Array.pop is destructive, for a non-destructive version have an index that you increment
makeRequest(names.pop(), function onResponse(statusCode, data) {
console.log(statusCode, data)
requestNames(callback)
})
}
requestNames(function(){
console.log('done')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment