I have defined a route in express that should contain multiple sql queries and i don't know how to structure it using promises and/or async/await.
Sql query A returns an id that is required in sql query B. Sql query B in turn returns three strings as an array that is required in sql query C. Sql query C consists of a loop that uses each of those strings of the array once. In this loop there are also if/else conditions to assign the return values to a specific variable.
These are my isolated queries:
A
connection.query('SELECT ID FROM Config WHERE ConfigID = ?', configid, function (error, result, fields) {
if (error) throw error;
else{
id = result[0].ID;
}
});
B
connection.query('SELECT Var1, Var2, Var3 FROM Config2 WHERE ID = ?', id, function (error, result, fields){
if (error) throw error;
else {
var varArray = [];
varArray.push(result[0].Var1, result[0].Var2, result[0].Var3);
}
});
C
for (i = 0; i < varArray.length; i++){
var selectedVar = varArray[i];
connection.query('SELECT Value FROM Config3 WHERE ConfigID = ? AND VarName = ? ORDER BY Timestmp DESC LIMIT 1', [configid, selectedVar], function (error, result, fields) {
if (error) throw error;
else if (i == 0){
aaa = parseInt(result[0].Value);
} else if (i == 1){
bbb = parseInt(result[0].Value);
} else if (i == 2){
ccc = parseInt(result[0].Value);
}
});
}
configid is predefined, so do not wonder where it comes from. A, B and C have to be connected in a way that they are executed sequentially.
Then there is another query D, that doe not need any of the previous values (except of the predefined configid), so it can be executed before the others have finished.
D
connection.query('SELECT Number FROM Config WHERE ConfigID = ?', configid, function (error, result, fields) {
if (error) throw error;
else{
ddd = parseInt(result[0].Number);
}
});
When all queries are done and the respective values have been assigned, i want to write them into a new array where all data is stored:
data = [];
data[0]= aaa;
data[1]= bbb;
data[2]= ccc;
data[3]= ddd;
How do i connect all these queries in a way i described it? I have already read several atricles about promises and async/await but i am struggling to apply it to my specific problem.