A little background; I work with node.js, and have found that many bugs are avoided by returning all callbacks in asynchronous code. For example:
function useMyAsyncFunc(stuff, c, callback)
myAsyncFunc(stuff.a, stuff.b, c, function (error, data) {
if (error) {
return callback(error);
}
// Long body of code in here.
return callback(null, data);
});
}
My question is, would it be better to do the above, considering that the chain of callbacks could be quite large, or would
function useMyAsyncFunc(stuff, c, callback)
myAsyncFunc(stuff.a, stuff.b, c, function (error, data) {
if (error) {
callback(error);
return;
}
// Long body of code in here.
callback(null, data);
return;
});
}
be more efficient?
Put more explicitly, does node benefit from the latter, where it is told to ignore the return value of the callback function?
I likewise agree that in general the "return callback()" does no harm nor does it significantly affect performance versus "callback(); return;". I decided to test that along with testing "process.nextTick(... cb ...); return;".
Try the following code:
'use strict';
var showComments = 0;
var counter = 10000;
var ab = process.argv[2];
function a(x, cb) {
var myCB = function (err, result) { x = result; }
x *= 1.01;
if (showComments) console.log('start counter =', counter, ', x = ', x);
if (--counter > 0) a(x, myCB);
if (showComments) console.log("cb'ing");
switch (ab) {
case 'a':
return cb(undefined, x);
case 'b':
cb(undefined, x);
return;
case 'c':
process.nextTick(function () { cb(undefined, x); });
return;
default:
console.log('Oops! Try typing "node testReturnCallBack.js [a|b|c]"');
process.exit(1);
}
}
var start = (new Date()).getTime();
a(1, function (err, result) {
console.log('final result = ', result);
var finish = (new Date()).getTime();
var diff = finish - start;
console.log('run took %d milliseconds', diff);
});
And you should see that cases 'a' and 'b' run multiple times return basically the same time in milliseconds while the computed value remains constant. Meanwhile case 'c' takes about 50% longer.