I am trying to insert a row into my FILE table, but when I attempt this the order in which things are done isn't what I want it to be. I know that JS is asynchronous but, I'm not sure how that affects how I should work within a loop.
Some background, sharedLib.serverCreateCalendar(file) just takes a .ics file and converts its content to a JSON so i can get the info out of it
I don't have much experience with JS or SQL so I don't have any idea what I should do to fix this.
for (var i = 0; i < files; i++) {
cals = sharedLib.serverCreateCalendar(file); // get the cal info as a JSON
var obj, fileN, version, prodID, evtNum; //variables for parsing the JSON and getting the values
var obj = JSON.parse(cals); //parse the calendar JSON
//Assign the values i want
fileN = files[j];
version = obj.version;
prodID = obj.prodID;
evtNum = obj.numEvents;
//SQL to insert into the FILE table
var calInsert = ("INSERT INTO FILE (file_Name, version, prod_id) VALUES('" + fileN + "'," + version + ",'" + prodID + "'" + ");"); //This is the SQL to insert into the FILE table with its required info
console.log(calInsert);
//Send the SQL query to add a file
connection.query(calInsert, function(err, result) {
if (err) { //error inserting into the DB
console.log("Calendar insert error");
res.send("Error");
} else { //if placing the calendar is good then add the events
console.log("Added the calendar!");
}
});
}
Ideally this would output
("INSERT INTO FILE (file_Name, version, prod_id) VALUES('" + fileN + "'," + version + ",'" + prodID + "'" + ");");
Added the calendar!
("INSERT INTO FILE (file_Name, version, prod_id) VALUES('" + fileN + "'," + version + ",'" + prodID + "'" + ");");
Added the calendar!
("INSERT INTO FILE (file_Name, version, prod_id) VALUES('" + fileN + "'," + version + ",'" + prodID + "'" + ");");
Added the calendar!
and so on until i'm done looping but, it outputs this instead
("INSERT INTO FILE (file_Name, version, prod_id) VALUES('" + fileN + "'," + version + ",'" + prodID + "'" + ");");
("INSERT INTO FILE (file_Name, version, prod_id) VALUES('" + fileN + "'," + version + ",'" + prodID + "'" + ");");
("INSERT INTO FILE (file_Name, version, prod_id) VALUES('" + fileN + "'," + version + ",'" + prodID + "'" + ");");
Added the calendar!
Added the calendar!
Added the calendar!