Javascript is a language heavy on callbacks. And as such, you quickly end up
with deeply nested anonymous functions.
Take the following example, which reads a file, parses the content, makes a
transformation, and writes it back out:
var fs = require('fs'),
input = 'input.json',
output = 'output.json';
fs.readFile(input, function(err, data) {
var content = data.toString(),
json = JSON.parse(content),
result = json.reduce(function(a, b) { return a + b; });
fs.writeFile(output, result, function(err) {
console.log('done');
});
});
Now, even as simple an example as this quickly becomes unreadable. But there is
a solution. A simple pattern flattens the code, and makes it much more readable:
var fs = require('fs'),
input = 'input.json',
output = 'output.json';
fs.readFile(input, fileRead);
function fileRead(err, data) {
var content = data.toString(),
json = JSON.parse(content),
result = json.reduce(sumNumbers);
fs.writeFile(output, result, writingComplete);
};
function sumNumbers(a, b) {
return a + b;
};
function writingComplete(err) {
console.log('done');
};
The same functionality, only now much more readable.