I was always wondering how are callback implemented. I always wandered (in Node.js) how does this work:
fs.readFile('mydata.txt', function (err, buffer) {
What returns an err? What returns a buffer?
I know these are callbacks, and I always strugled to learn them. So, I wrote my own simple implementation in order to understand it.
Can someone please see this simple example. It comes from my head, since I took my time to understand it what I do. Of course, this might be totally wrong.
I would love to hear your comments. Before I abandon Callback in favor of Promises, I want to 100%understand them!!!
My Example:
function Executor (callback, nameParam) {
callback(1,6, function (err, result) {
if (err) {
console.log(err);
} else {
console.log(result)
}
});
}
function calculator(num1, num2, returnStuff) {
var err, result, internalResult;
internalResult = num1 + num2;
if (internalResult < 3) {
returnStuff(err = "Number is lower then three", result);
} else {
return returnStuff (err, result = "Number is larger then three");
}
}
Executor(calculator, "John");