Wait for loop to finish?
please how I can make my my code to wait for the for loop to be finished then send the response.
router.get('/employeedept', (req,res) => {
db.query('select * from users where departement=? and username!=?',[depar,req.user[0].username],function(err,results){
if(err) throw err;
for(let i = 0; i < results.length; i++){
db.query('select * from objectives where person_id=?',[results[i].id],function(err,objectives){
if (err) throw err;
if(objectives[0]){
results[i].objectives=objectives;
}
});}
res.json(results);
})
});
You can promisify the db.query
function to avoid multiple callbacks, and simplify your query with a JOIN
statement:
const { promisify } = require('util');
const query = promisify(db.query).bind(db);
router.get('/employeedept', async (req, res) => {
const results = await query(`SELECT * FROM objectives as O
JOIN users AS U
ON U.id = O.person_id
WHERE U.departement = ?
AND U.username != ?`, [ depar, req.user[0].username ]);
return res.json(results);
});