I am very new to NodeJS and Express and struggling to use sqlite3
module.
Let's assume I have a database with 2 tables: cars, car_details.
This is a simple example of what I am trying to do:
router.get('/get-car-info', (req, res) => {
let car_details = [];
let sql = '';
let cars = ['audi', 'bmw', 'benz', 'honda', 'toyota];
cars.forEach(car => {
sql = `SELECT * FROM car_details WHERE name=${car}`;
db.get(sql, function(err, data) {
if (!err) {
car_details.push(data);
}
});
});
res.json({ 'success': true, 'cars': car_details });
});
This is a basic example but its enough to describe the problem.
Since db.get
is async request, by the time the loop is done, the response is empty since it gets called before queries are finished.
If there was just one query then fine, I would send the response within callback
but not sure how to achieve that when having a loop/recursion situation.
Thanks in advance...