0

so I am trying to create a function that checks if the name of an author is already saved in my database. I am a beginner with Node.js, so I am not used to working with modules, I have always used OOP.

    exports.checkAuthor = function(authorName) {
    var inDatabase;
    conn.connect(function(err) {
        if (err) throw err;
        console.log("Connected!");
        var sql = `SELECT COUNT(*) AS 'countResult' FROM Author WHERE Name LIKE '${authorName}'`;
        conn.query(sql, function (err, result) {
          if (err) throw err;
          inDatabase = (Object.values(result[0])[0] == 1)? true:false;
          return inDatabase;
        });
        conn.end();
    });
} 

It should return either true or false depending on if the value stored is 1 or 0. And I am trying to get the return value like this:

console.log(db.checkAuthor('Drake'));

But it keeps returning undefined... I checked and the value of

inDatabase = (Object.values(result[0])[0] == 1)? true:false;

is in fact always true or false. Thanks for any help!

Accio
  • 74
  • 1
  • 8
  • Does this answer your question? [What is the purpose of Node.js module.exports and how do you use it?](https://stackoverflow.com/questions/5311334/what-is-the-purpose-of-node-js-module-exports-and-how-do-you-use-it) – rotimi-best Apr 27 '20 at 09:58
  • how are you importing `db` into the other file where you are calling `db.checkAuthor`? Or in other words when you do `console.log(db)` what do you get? I am assuming you are not doing the import right – rotimi-best Apr 27 '20 at 09:59
  • 1
    Your `checkAuthor()` function has NO return value at all. The `return inDatabase;` statement is two levels embedded in callbacks and all that does is return from those callbacks which go nowhere. You probably need to study this [How do I return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323#14220323) which is the canonical answer here for questions like this. In case you were wondering, you can't return that value directly. You have to use a callback promise or event to get the value out. – jfriend00 Apr 27 '20 at 10:01
  • 1
    And, before you write any more code, I would suggest you get the version of your database that supports promises because it will be a LOT easier to program with. You will have to learn how to use promises, but that will be way better than dealing with these plain asynchronous callbacks, particularly when combining multiple asynchronous operations like this. And, once you start using promises, you can then use `async/await` which further simplifies writing this type of code. – jfriend00 Apr 27 '20 at 10:04

0 Answers0