This is really useful when such projects break everything down into small units. Thus, asynchronous parts may be contained or offered in ways that facilitate reasoning. It sounds like you want to use async/await , which is suitable for this, but that means you need to generate promises. The last time I checked the standard MySQL library, this is not done, but it's easy enough to wrap them.
So, I would break it like this:
function check_growth_items(room){ //simple function to get growth items return new Promise((resolve, reject) => { sql = "select growth_items from garden where room_id = ?"; db_connection.query(sql, [room], function (err, result){ if (err){ console.log("Garden Error: " + err); reject(err); } resolve(result) }) }) } function get_food(type, room_id){ // expects a type [vegetable | fruit] and room return new Promise((resolve, reject) => { sql = "select name, qty from ? where room_id = ?"; db_connection.query(sql, [type, room_id], function (err, result){ if (err){ console.log("An vegetable error has occurred: " + err); reject(err); } resolve(result); }); }) }
Now all your asynchronous things are simple. In an async function, you can call something like:
let items = await check_growth_items(socket.room)
or get food:
fruit[socket.room] = await get_food('fruit',socket.room )
or
get_food('fruit',socket.room ) .then(result => fruit[socket.room] = result) .catch(err => console.log(err))
I'm admittedly not 100% sure what the final code should do, but your main function should be able to look something like this:
async function starter (){ // it not clear in your code how you're using this // of it the other async calls depend on the return value var growth_items = await check_growth_items(socket.room) if (!vegetables[socket.room]) { vegetables[socket.room] = await get_food('vegetables',socket.room ) } if (!fruit[socket.room]) { fruit[socket.room] = await get_food('fruit',socket.room ) } console.log(vegetables[socket.room]); console.log(fruit[socket.room]); }
This probably won't be the solution for cutting and pasting, but hopefully gives you some ideas on more convenient ways to organize fragments.