Johnson Doe
Johnson Doe

Reputation: 179

NodeJS returning true/false inside function

I currently have code like this

function userExists(userID) {
   connection.query(query, function(error, results, fields) {
       if(results.length > 0) {
           return true;
       }
       return false;
   });
}

My intention is to have this return as true if a result is found, and false if it doesn't. This doesn't work due to returning a function inside of a function, how would I fix this so I could still do if(userExists(id)) { code }

Upvotes: 3

Views: 10536

Answers (1)

Mico
Mico

Reputation: 2009

You will need to use a Promise or a callback function.. Here is an example how to implement the function using a promise:

function userExists(userID) {
   return new Promise(function(resolve, reject) {
       connection.query(query, function(error, results, fields) {
           resolve(results.length > 0);
       });
   }
}


userExists(1).then(function(result) {
  // Here result will be either true or false.
}

You probably can use ES6 syntax if you are running node so you can also write

const userExists = userID => new Promise((resolve, reject) => {
   connection.query(query, (error, results, fields) => {
       resolve(results.length > 0);
   });
});

userExists(1).then(result => {
    console.log(result);
});

EDIT:

If you for some reason needed to implement this using a callback function here is how you would do it.. Use of Promises are preferred though.

const userExists = (id, callback) => {
    connection.query(query, (error, results, fields) => {
        callback(results.length > 0);
    });
}

userExists(1, result => {
    console.log(result);
});

Upvotes: 3

Related Questions