Reputation: 3520
I'm wondering whether the return is required at the end of this example Express function. I've seen many examples where the return isn't included and some where it is. (I'm also not sure why the result is converted to string and then back to JSON, but that's a different question.)
/**
* @param {string} id
* @param {function} callback
*/
function getPersonCount (id, callback) {
connection.query('SELECT COUNT(id) as count FROM people WHERE id=?;', [id], function(err, result) {
var string = JSON.stringify(result);
var json = JSON.parse(string);
var count = json[0].count;
callback(count);
return callback;
});
}
Upvotes: 0
Views: 148
Reputation: 1163
You only have to return your callback example :
function getPersonCount (id, callback) {
connection.query('SELECT COUNT(id) as count FROM people WHERE id=?;', [id], function(err, result) {
var string = JSON.stringify(result);
var json = JSON.parse(string);
var count = json[0].count;
callback(count);
});
}
To use this function you have to do something like this :
getPersonCount (id, function(result){
//here you can use the data from your function
console.log(result)
})
Upvotes: 1
Reputation: 1075219
To be clear: You're returning callback
from the anonymous callback you're passing into query
.
TL;DR No, you almost certainly don't want to return it, though it's probably harmless if you do.
It has nothing to do with Express, it has to do with that query
function. If it expects the callback you give it to return a function that it will do something with, then you should return an appropriate function (whether callback
is that function is a question, and I suspect the answer would be no, but...). If not, no, you shouldn't.
I'd say the odds are extremely high that query
completely ignores the return value of the callback you're passing it.
Upvotes: 2