I am fairly new to Javascript and am currently working on a project using a MySQL server and NodeJS.
The problem I am having is that when I attempt to push the results of the MySQL query to a global array, the array comes back completely empty. Is there something I am doing wrong or some additional steps that someone can explain to me?
Relevant code:
var itemList = [];
var siteList = [];
function getItems(){
con.connect(function(err) {
try{
if (err) throw err;
con.query("SELECT DISTINCT ProductURL FROM products;", function (err, result, fields) {
if (err) throw err;
for (i=0; i<result.length; i++){
itemList.push(result[i].ProductURL);
}
});
} finally{
con.end();
}
});
async function another_function() {
//Does some stuff with the information in the itemList array and inputs to siteList
}
async function anofuncV2() {
//does more stuff with the information provided by another_function
}
let result = await getItems();
itemList.forEach(another_function);
anofuncV2(siteList);
The connection itself is fine and tested as well as a console.log right after the array push comes back with the correct information.
Additional note: I do need it as a global array for the other functions to work properly, I do know I could put it after the push to work, but that isn't what Im looking for
Edit 1: I understand that the code is asynchronous, but the entire concept of asynchronous code confuses me not matter how much I research it. So if someone could give a simple explanation that would be wonderful.
What I understand:
- It runs at the same time as synchronous code causing the other code to run before the information can be input into the array