So I am currently working on a basic prototype and been running into some errors. I have a function that adds a user into the database. Before doing so, I made it read and execute a function to check the highest value of id, and then add it into the next query. But when I try to do this my query to add a user to the database is always executed before I get the value back from the database.
After doing some research, I found I will probably have to use async functions. I have been trying to find an answer that can suite my problem but can't seem to find an example that could work for me, I have seem many ways to write them out.
My code is this
async function maxIDD(maxID){
try{
connection.query('SELECT MAX(id) as maxID FROM users', (err,rows) => {
var maxID = rows[0].maxID;
console.log(maxID);
})
}
catch (error) {
console.log(error);
}
return maxID;
}
async function addData(){
const maxID2 = await maxIDD(maxID) + 1
console.log('macidvalue = ' + maxID2)
let sql = "INSERT INTO users (name, num, id, quantity) VALUES('"+ dataObject.userName +"','"+ dataObject.userNum +"','"+ maxID2 +"','"+ dataObject.userQuantity + "')";
console.log(sql);
connection.query(sql);
The first function maxIDD() is the one where I run the query to check the max id, then addData() is to add the user to the database.
This is where I am at currently, I am trying, to follow this answer "https://stackoverflow.com/questions/50751048/node-js-waiting-for-variable-to-be-set?answertab=active#tab-top"
Yet when I try and return my value (in this case maxID) It just get saved as "macidvalue = [object Promise]"
Not sure how I could solve this. All I need to do is query the database, and use that value somewhere else. Does anyone have any recommendations or suggestions?