Reputation: 3
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);
})
});
Upvotes: 0
Views: 86
Reputation: 364
It is possible to create a local promise then attach onResolve function.
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;
var p = new Promise((resolve, reject) => {
for (let i = 0; i < results.length; i++) {
db.query('select * from objectives where person_id=?', [results[i].id], function (err, objectives) {
if (err) {
reject(err);
throw err;
}
if (objectives[0]) {
results[i].objectives = objectives;
}
});
}
resolve();
});
p.then(() => res.json(results));
});
});
Fix update:
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;
var promiseArr = [];
for (let i = 0; i < results.length; i++) {
var promise = new Promise((resolve, reject) => {
db.query('select * from objectives where person_id=?', [results[i].id], function (err, objectives) {
if (err) {
reject(err);
throw err;
}
if (objectives[0]) {
results[i].objectives = objectives;
}
resolve();
});
});
promiseArr.push(promise);
}
Promise.all(promiseArr).then(() => res.json(results));
});
});
Upvotes: 0
Reputation: 531
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);
});
Upvotes: 1