Reputation: 33
I am performing database connection in nodejs module. But its callback is not called.
Here is my module-
*getChapterList.js
var mysql=require('mysql');
var client=mysql.createClient({
user:'mysql',
password:''
});
client.useDatabase('test');
module.exports.get_chapter_list = function(subject_id){
client.query("select distinct chapter_id from course_associations where subject_id="+subject_id+" and status_id=1",
function(err,results,fields){
return results;
});
return "hello";
};
Now i am calling this module as-
rs=require('./getChapterList');
rs.get_chapter_list(1);
// Output: hello
but expected o/p is results array.
Googled alot.but no result..
Upvotes: 3
Views: 4171
Reputation: 3026
You need to return the results asynchronously:
exports.get_chapter_list = function(subject_id, callback) {
client.query("select ...", callback);
};
...
var rs = require('./getChapterList');
rs.get_chapter_list(1, function(err, results) {
if (err) {
// handle error
} else {
// do something with results
console.log(results);
}
});
Upvotes: 3
Reputation: 1569
scttnlsn answer is correct, as I have faced this issue and had solved by just passing the callback function as a argument.
Try for that:
var mysql=require('mysql');
var client=mysql.createClient({
user:'mysql',
password:''
});
client.useDatabase('test');
module.exports.get_chapter_list = function(subject_id, callback){
client.query("select distinct chapter_id from course_associations where subject_id="+subject_id+" and status_id=1",
function(err,results,fields){
callback( results );
});
return "hello";
};
And then
var rs = require('./getChapterList');
rs.get_chapter_list(1, function(results) {
console.log(results);
}
});
This will print the desire output.
Upvotes: 0
Reputation: 35008
The callback will be called after the query completes and the return value of results will be passed back to the method that created the callback, which then discards it.
The reason why the output is "hello", is because that's what the get_chapter_list
function returns.
What happens is:
get_chapter_list
functionclient.query
fires off a request to the databaseclient.query
function returns.get_chapter_list
function returns "hello".client.query
) which discards it).To get what you want you'll probably need to think asynchronously.
Define the method as
module.exports.get_chapter_list = function(subject_id, callback){
client.query("select distinct chapter_id from course_associations where subject_id="+subject_id+" and status_id=1",
function(err,results,fields){
// doesn't contain any error handling
callback(results);
});
};
and then call the method:
rs.get_chapter_list(1, function(results) {
console.log(results); // or whatever you need to do with the results
});
Upvotes: 3