Mongoose: Return and Callback

Posted on Feb 02, 2017

Mongoose: Return and Callback

Ever wondered why Mongoose’s JavaScript has both a return and a callback in the same line?

Typically in asynchronous programming techniques, it is a good practice to use a return statement along with callbacks at specific points. For example, when the code has another callback further down. This prevents accidental execution of multiple callbacks within the same function.

Here is a very simple example:

var failureCallback = function(err) {
console.log("Failed");
// do something with err
}

var successCallback = function(data) {
console.log("Success");
// do something with data
}

var asyncFunction = function(failureCallback, successCallback) {
getDataFromDb(err, data) {
if(err) {
failureCallback(err);
}
successCallback(data);
}
}

In this case if there is an error, the first callback will definitely be called, but the second callback may also be called simultaneously. So the console output might be:

Failed
Success

To prevent this, you simply add a return statement to the failureCallback:

var asyncFunction = function(failureCallback, successCallback) {
getDataFromDb(err, data) {
if(err) {
return failureCallback(err);
}
successCallback(data);
}
}

Therefore, it is not the case that you can only use return or callback but not both. In fact in some case you must use them together.

All of this to say that, it is possible that in the case of your Mongoose examples, it may be a requirement by the function (although it does not seem so) but it may as well be a force of habit of the original author to use return along with callback. Depending on the context, both are correct. Using return could be either a necessary or unnecessary precaution in these use cases.