Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs- callback in modules not working

Tags:

node.js

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..

like image 704
sumit gandhi Avatar asked Dec 02 '25 09:12

sumit gandhi


1 Answers

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:

  1. You call the get_chapter_list function
  2. The client.query fires off a request to the database
  3. The client.query function returns.
  4. The get_chapter_list function returns "hello".
  5. The SQL query completes and calls the callback
  6. Your callback method is called and does nothing (it just returns the results, but that return value is handed back to the caller of the callback (somewhere within 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
});
like image 147
beny23 Avatar answered Dec 04 '25 00:12

beny23



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!