Last active
August 29, 2015 14:12
-
-
Save mixmix/b9573a0bfceea972aeca to your computer and use it in GitHub Desktop.
refacrotring callbacks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require('http') | |
var completeCount = 0 | |
var dataStore = [] | |
for (var i=0; i<(process.argv.length-2); i++) { | |
dataStore[i] = { | |
url: process.argv[i+2], | |
response: '' | |
} | |
} | |
dataStore.forEach( function(record) { | |
http.get(record['url'], function(response) { | |
response.setEncoding('utf8') | |
response.on('error', console.error) | |
response.on('data', function store(data) { | |
record['response']+= data | |
}) | |
response.on('end', function() { | |
completeCount++ | |
if (isLastFinished()) { | |
printResponses() | |
} | |
}) | |
}) | |
}) | |
/***** **Attempted refactor** ******** | |
dataStore.forEach( function(record) { | |
http.get(record['url'], processResponse); | |
}) | |
var processResponse = function(response) { | |
response.setEncoding('utf8') | |
response.on('error', console.error) | |
response.on('data', store) | |
response.on('end', function() { | |
completeCount++ | |
if (isLastFinished()) { | |
printResponses() | |
} | |
}) | |
} | |
var store = function(data) { | |
console.log('.') | |
record['response']+= data | |
} | |
*/ | |
var isLastFinished = function() { | |
return (completeCount === dataStore.length) | |
} | |
var printResponses = function() { | |
dataStore.forEach( function(record) { | |
console.log(record['response']) | |
}) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
a common pattern you're missing here is creating a function that takes in arguments and returns a second function with the arguments as variables for the second function.
for example, we can make a function that takes in a single number argument
x
and returnsx + 10
.or we can create a function that takes in a single number argument
n
and returns a function that takes in a single number argumentx
and returnsx + n
.we call this pattern a closure.
both
processResponse
andstore
require access torecord
, so they should be wrapped in a function that takes them as an argument.