Skip to content

Instantly share code, notes, and snippets.

@tpott
Created April 17, 2013 03:02
Show Gist options
  • Save tpott/5401472 to your computer and use it in GitHub Desktop.
Save tpott/5401472 to your computer and use it in GitHub Desktop.
javascript callbacks
// this first version uses a function callback to pass in the object reference...
for (var i = 0; i < files.length; i++) { // WORKS
var setFile = function(file) {
return function(err, data) {
if (err) throw err;
file[1] = data;
};
};
fs.readFile(files[i][2], 'utf8', setFile(files[i]));
}
// compared with
for (var i = 0; i < files.length; i++) { // DOESN'T WORK
fs.readFile(files[i][2], 'utf8', function(err, data) {
if (err) throw err;
file[i][1] = data;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment