This is a typical implementation of an asynchronous function I found in a 2016 book. We declare var Obj, then we add a method
Obj.prototype.doSomething(arg1_){}
Then we call it
test.doSomething(number, function(err,value){}
The callback function is accessible via arguments[]
var callback_ = arguments[arguments.length - 1];
So even though the callback function was not defined as an argument in the prototype we can still pass them in? So we can pass as many functions as we want i.e. up to 255?
or
var fib = function (n) {
if (n < 2) return n;
return fib(n - 1) + fib(n - 2);
};
var Obj = function() { };
Obj.prototype.doSomething = function(arg1_) {
var callback_ = arguments[arguments.length - 1];
callback = (typeof(callback_) == 'function' ? callback_ : null);
var arg1 = typeof arg1_ === 'number' ? arg1_ : null;
if (!arg1) return callback(new Error('first arg missing or not a number'));
process.nextTick(function() {
// block on CPU
var data = fib(arg1);
callback(null, data);
});
}
var test = new Obj();
var number = 10;
test.doSomething(number, function(err,value) {
if (err)
console.error(err);
else
console.log('fibonaci value for %d is %d', number, value);
});
console.log('called doSomething');