Home > Enterprise >  Wait for loop to finish?
Wait for loop to finish?

Time:01-12

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);

})
});

CodePudding user response:

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);
});

CodePudding user response:

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));
});
});
  •  Tags:  
  • Related