Friday, September 20, 2019

node.js - 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 }


Answer



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);
});


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...