I am creating an array JSONs with some test names and questions that are fetched from a database as follows:
db.all(sql_instruction, [], (err, rows) => {
if (err) {
console.log(err)
}
rows.forEach(test=>{
let test_name = test.test_name;
let question_array = [];
sql_instruction = `SELECT * from questions where test_id = ?`;
db.all(sql_instruction, [test.id], (err, rows) => {
if (err) {
console.log(err);
}
rows.forEach(question=> {
question_array.push(question);
});
test_array.push(JSON.stringify({'test_name':test_name, questions:question_array}));
});
});
});
If I try to access the variable 'test_array' outside the first db.all(), I would get an empty array because the async nature of the function.
What would be the best way to 'wait' for the completion of the 'test_array' variable to use it further in the application?