Reputation: 3060
I'm trying to use a callback to get the result of a query from a database, but I am still getting undefined returned to me. Here is the code:
function onComplete(x){
return x;
}
function getRecords(callBack){
mongo.MongoClient.connect("mongodb://localhost:27017/nettuts", function(err, db){
if(err){
console.log(err);
return;
}
console.log('Connected to mongo');
db.collection('nettuts').find().toArray(function(err, records){
if(typeof callBack === "function"){
callBack(records);
}
});
});
}
app.get('/', function (req, res) {
var records = getRecords(onComplete);
console.log(records);
res.render("index", {title: "Hello!", people: records});
});
On the third to last line, I am getting an undefined.
Upvotes: 0
Views: 71
Reputation: 151072
As stated, you are following this the wrong way around for asynchronous programming, if you want "re-use" then you are passing in the callback to the function you are re-using and not the other way around:
var mongo = require("mongodb"),
MongoClient = mongo.MongoClient;
function getRecords(db,callback) {
if (typeof callback !== 'function')
throw "getRecords() requires a callback as the second arg";
db.collection("test").find().toArray(function(err,records) {
callback(err,records);
});
}
MongoClient.connect('mongodb://localhost/test',function(err,db) {
getRecords(db,function(err,result) {
if (err) throw err;
console.log(result);
});
});
Also noting here that any of your active code needs to happen "after" the connection is present, too broad to cover here on the best way to do that. But you certainly do not establish a connection with every request, as that would be very bad.
You "re-usable" function then just accepts the connection details and the actual functionality you want to happen when the operation is complete. That is the basic principle of callbacks.
Upvotes: 1