Reputation: 200
I’m learning to really love ES5’s .bind()
as it allows me to modify the context of callback functions and really solves for most callback hell or pyramiding issues.
However, I’m wondering if its generally considered best practices to utilize the optional args parameters. Being able to inject dependencies seems incredibly useful, but used incorrectly could lead to really hard to untangle spaghetti code.
Example:
function loadFile(filename, callback) {
fs.exists(function (exists) {
if (exists) {
fs.readFile(filename, 'utf8', function (err, data) {
callback(data);
});
}
});
}
// becomes
function onReadFile(callback, err, data) {
callback(data);
}
function onExists(filename, callback, exists) {
if (exists) {
fs.readFile(filename, 'utf8', onReadFile.bind(this, callback));
}
}
function loadFile(filename, callback) {
fs.exists(onExists.bind(this, filename, callback));
}
Should I just stick to nesting my functions or use the optional arg params?
Upvotes: 0
Views: 208
Reputation: 664990
Yes, partial application is a very beneficial practise. There's nothing wrong with using it. Callback hell in contrast is known as an antipattern.
Upvotes: 2