My problem today has something to do with promises inside loops. Right down here I'll put my code and as you can see it does a few things. First of all it loop inside all my events and splits the date it finds inside of it into 3 fields to insert it into a SQL db.
In total I fill 2 tables, one with the dates and one with the actual events. The problem is that when this code gets executed, it loops all the way to the end and does the date assignments all at once and then it starts releasing the promises. That makes my function insert x times the same date and event (where x is the lenght of my events array).
Now, why is this happening? I studied and implemented promises exactly for this problem but it seems to still be around. Can someone explain to me what am I doing wrong? Also, do you think this code is a bit too "pyramid of doom" like? Thanks a lot in advance!
events.forEach(function (event) {
// Simple date formatting
dayFormatted = event.day.split("_");
year = dayFormatted[0];
month = dayFormatted[1];
day = dayFormatted[2];
// Check if the row already exists ...
SQLCheckTableRow(`day`, year.toString(), month.toString(), day.toString()).then(function (skip) {
// ... if not it skips all this part
if (!skip) {
// Create, if it doesn't exist already, a date table that is going to be connected to all the events and fill it
SQLFillTable(`date, `null, "${year}" , "${month}" , "${day}", null`).then(function () {
let values = []
event.ons.forEach(function (on) {
on.states.forEach(function (event) {
values = [];
values.push(Object.keys(event.data).map(function (key) {
return event.data[key];
}));
SQLFillTable(`event`, values).then();
})
})
})
}
})
})