I have a javascript function which is intended to output a 0 if a mysql table doesn't exist and a 1 if it does. But I have not been able to understand why it does not function as intended.
function TableExistsOrNot (checktable){
try{
console.log("the function was entered");
var sqlcheck = 'SELECT id FROM ?? ORDER BY id DESC LIMIT 1';
con.query(sqlcheck,[checktable],function (err, result) {
if (result > 0){
console.log(result);
console.log("table exists");
return 1;
}
if(result === undefined){
console.log("result was undefined");
return 0.0;
}
});
}
catch (err) {
console.log(err);
console.log("error locating table");
return 0;
}
}
When I console log the result it just says undefined. And if I try to assign the result of the function to a variable it also says undefined.
edit based on the feedback I have added code for async nature, installed and required express. But this has not solved the problem. See the code below. What is strange is console.log(a);
in the else statement is logging 5. But the last line console.log(datatablepresent);
which should be equal to 'a' is logging Promise { <pending> }
function checktable(tablename) {
try{
let sql = 'SELECT id FROM ?? ORDER BY id DESC LIMIT 1';
return new Promise((resolve, reject) => {
con.query(sql,[tablename],(err, result) => {
if (err) {
console.log("entered err");
}
else {
resolve(result);
console.log("entered else");
var a = result[0].id;
if (a>1){
console.log(a);
return a;
}
}
});
});
}
catch (err) {
console.log(err);
console.log("error locating table");
//return 0;
}
}
app.get("/", async function (req, res) {
console.log("entered callback");
const result = await checktable();
res.send(result);
console.log(result);
});
datatablepresent = checktable('beta5');
console.log(datatablepresent);