I'm trying to make a function that returns true if it detects a row containing a value in a specific column in nodejs.
I've tried to use the result variable from query() without any success :
let rowexists = (mystring) => {
let exists = false;
let sql = "SELECT EXISTS( SELECT 1 FROM mytable WHERE `mycolumn` = '" + mystring + "')";
connection.query(sql, function(error, result, field){
console.log((result[sql]));
console.log(exists);
exists = (result[sql]);
});
return exists;
}
console.log(rowexists("myvalue"));
Event if there is a row with the value "myvalue" (there is), rowexists() always returns false.
My problem isn't really the fact that this is async, it's the fact that both
console.log((result[sql]));
and
console.log(exists);
return undefined.
A promise is something that is useful in this type of situation.
The issue that you are having, is that your query hasn't finished running by the time the function returns. So, having a promise returned, we can return the value at a later time.
Side Note: You should be using prepared queries when using an SQL database.
let rowexists = (mystring) => {
// Return a new promise
return new Promise(resolve => {
// Create the sql query (this uses placeholders)
// Hard coded values don't need to be placeholders but just for example:
let sql = "SELECT 1 FROM ?? WHERE ?? = ?";
// Query the database replacing the ?? and ? with actual data
connection.query(sql, ['mytable', 'mycolumn', mystring], function(error, result, field){
// Result will either be undefined or a row.
// Convert it to a boolean and return it.
resolve(!!result)
});
});
}
// Get the data
rowexists("myvalue").then(result => console.log(result))
Self invoking function using async/await:
(async function() {
let exists = await rowexists('myothervalue')
console.log(exists)
// The rest of your related code
})()
If you don't like the then()
syntax, you can use async/await
. Here are two ways in which you can do so:
Basic function using async/await:
async function test() {
let exists = await rowexists('mythrirdvalue')
console.log(exists)
// The rest of your related code
}
test()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.