I am trying to figure out the proper way to call a function asynchronously if it is also making asynchronous calls to the database.
In my code I call a function called 'check_foods()` which will query a database up to two times if it has not been called already. The database queries will populate the two variables vegetables and fruit (assuming they haven't been populated already). Once the function returns I want to make use of those variables.
However, I assume that the way my code is now that it will try to begin processing the two console lines even if it hasn't pulled the data from the database yet. Am I correct in this assumption? If so, what should I do to implement this correctly?
A simplified version of my code looks like this:
var vegetables = {};
var fruit = {};
async function starter (){
sql = "select growth_items from garden where room_id = ?";
db_connection.query(sql, [socket.room], function (err, result){
if (err){
console.log("Garden Error: " + err);
return;
}
console.log(result);
check_foods();
//Should not get to this point until variables have been populated
//However, due to the async nature of the code this does not seem to be implemented correctly.
//process vegetables[socket.room] and fruit[socket.room]
console.log(vegetables[socket.room]);
console.log(fruit[socket.room]);
});
}
async function check_foods(){
//Check to see if vegetables[socket.room] already exists, otherwise load it from the database
if (typeof vegetables[socket.room] !== "undefined"){
sql = "select name, qty from vegetables where room_id = ?";
db_connection.query(sql, [socket.room], function (err, result){
if (err){
console.log("An vegetable error has occurred: " + err);
return;
}
vegetables[socket.room] = result;
});
};
//Check to see if fruit already exists before looking up again
if (typeof fruit[socket.room] !== "undefined"){
sql = "select name, qty from fruit where room_id = ?";
db_connection.query(sql, [socket.room], function (err, result){
if (err){
console.log("An fruit error has occurred: " + err);
return;
}
fruit[socket.room] = result;
});
};
}
queryfunction. then you can doawait db_connection.query(...), and the code will be executed "synchronously"awaitdoes not make things execute synchronously and telling someone that is just misleading. It allows you to write code in a more synchronous looking way, but the code is all still executing asynchronously, event loop not blocked, other events being served, etc...awaitis pure syntactical sugar. One has to first understand promises and asynchronous code design and then one could useawaitto save a few lines of code.async/await. Without promises you can't really use it.mysqllibrary.