Slinky Slinky - 1 month ago 6
Node.js Question

Proper usage of a callback handler in Node

I am trying to get data that is being returned in a callback but my callback function (callbackFunc()) is not being executed, probably due to the way I am approaching this.If someone would point me in the right direction I would be grateful.

Thanks

var url = 'mongodb://localhost:27017/bac';
var term = 'usa';

MongoClient.connect(url, function(err, db) {

assert.equal(null, err);
findDocument(term.toUpperCase(),'country_code', db, function() {db.close();});

});



function callbackFunc(data){

console.log("inside callbackFunc()...");
console.log(data);

}

var findDocument = function(term, field, db, callbackFunc){
var collection = db.collection('bac');
collection.findOne({'country_code' : term}, function(err, document){
assert.equal(err,null);
console.log("Found this matching record for "+term);
console.log(document);
callbackFunc(document);
});
}

Answer

Let see your code:

findDocument(term.toUpperCase(),'country_code', db, function() {db.close();});

You pass wrong callback function, you pass function() {db.close();}.

i think you want pass:

function callbackFunc(data){

  console.log("inside callbackFunc()...");
  console.log(data);

}

so plese use:

findDocument(term.toUpperCase(),'country_code', db, callbackFunc);
Comments