Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS returning true/false inside function

Tags:

node.js

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 }

like image 522
Johnson Doe Avatar asked Aug 11 '26 21:08

Johnson Doe


1 Answers

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);
});
like image 73
Mico Avatar answered Aug 13 '26 12:08

Mico



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!