JavaScript tips - Unnest callbacks and method declarations
1. JavaScript Tips
Unnest Callbacks and Method Declarations
to improve readability and performance
Akbar S. Ahmed
Founder, Exponential.io – Build better apps faster with less effort.
Twitter: @exponential_io
Web: www.Exponential.io
3. Response time is 290 ms.
Nested Callback
#!/usr/bin/env node
var fs = require('fs');
fs.readFile('./file1.txt', function (err, file1Contents) {
if (err) throw err;
fs.readFile('./file2.txt', function (err, file2Contents) {
if (err) throw err;
var file3Contents = [file1Contents, file2Contents].join('');
fs.writeFile('file3.txt', file3Contents, function (err) {
if (err) throw err;
console.log('Concatenated file1.txt and file2.txt into file3.txt.');
});
});
});
4. Response time is 114 ms.
Unnested Callback: Properties
#!/usr/bin/env node
var fs = require('fs');
fs.readFile('./file1.txt', readFile1);
function readFile1(err, data) {
if (err) throw err;
writeFile3.file1Contents = data;
fs.readFile('./file2.txt', readFile2);
}
function readFile2(err, data) {
if (err) throw err;
writeFile3.file2Contents = data;
var file3Contents = [writeFile3.file1Contents, writeFile3.file2Contents].join('');
fs.writeFile('file3.txt', file3Contents, writeFile3);
}
…
5. Response time is 114 ms.
Unnested Callback: File Globals
#!/usr/bin/env node
var fs = require('fs');
var file1Contents, file2Contents, file3Contents;
fs.readFile('./file1.txt', readFile1);
function readFile1(err, data) {
if (err) throw err;
file1Contents = data;
fs.readFile('./file2.txt', readFile2);
}
function readFile2(err, data) {
if (err) throw err;
file2Contents = data;
file3Contents = [file1Contents, file2Contents].join('');
fs.writeFile('file3.txt', file3Contents, writeFile3);
}
…
7. Response time is 280 ns (that’s nanoseconds).
Nested Method Declaration
#!/usr/bin/env node
function Cat(name) {
this.getName = function () {
return name;
};
this.setName = function (n) {
name = n;
};
}
var meows = new Cat('meows');
console.log('I am a cat named ' + meows.getName());
8. Response time is 7 ns (that’s nanoseconds).
Unnested Method Declaration
#!/usr/bin/env node
function Cat(name) {
this._name = name;
}
Cat.prototype.getName = function () {
return this._name;
};
Cat.prototype.setName = function (n) {
this._name = n;
};
var meows = new Cat('meows');
console.log('I am a cat named ' + meows.getName());
9. npm install -g exponential
• Exponential.io alphas recently released
• Your input would be greatly appreciated
• Email: akbar@exponential.io
• Twitter: @exponential_io