3

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 }

Johnson Doe
  • 159
  • 4
  • 11
  • 1
    I'm afraid this can't be done in simple JS, because `connection.query` can take some time to process, therefore `userExists()` function should block. But JS does not support any blocking operations, afaik. So you should make `userExists` accept a callback and employ asynchronous style. – yeputons Feb 03 '17 at 08:59
  • 1
    Possible duplicate of [How to make a function wait until a callback has been called using node.js](http://stackoverflow.com/questions/5010288/how-to-make-a-function-wait-until-a-callback-has-been-called-using-node-js) – yeputons Feb 03 '17 at 09:02
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Ben Fortune Feb 03 '17 at 09:05

1 Answers1

3

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);
});
Mico
  • 1,978
  • 2
  • 13
  • 17
  • Hey man thanks a ton this is exactly what I was looking for, I fixed the ES6 version though, there was a missing ) and an extra }. – Johnson Doe Feb 03 '17 at 09:16
  • @JohnsonDoe Thanks. I also added an example how you would do this using a callback function if you are interested. – Mico Feb 03 '17 at 09:49