I'm' trying to create a 'groupe' and then insert its creator as administrator in 'groupemembers' table, however the second query gets skipped
router.post('/createGroupe/:userId', upload.single('file'), (req, res) => {
let groupe = req.body
// req.body containing the groupe title, description
let userId = req.params.userId
let groupeId
groupe['image'] = req.file
db.query('insert into groupes set ?', groupe, function(err, result){
if (err) throw err;
groupeId = result.insertId.toString()
db.query("insert into groupemembers set ?", [groupeId, userId, 'admin'], function (err, result){
console.log(groupeId)
if (err) return err;
})
res.send(result.insertId.toString())
})
})
CodePudding user response:
you need to learn callback style or even better async/await style. much more easier to code.
but for your specific concern, i think you wanted to put the res.send one line up because that way you will call res.send AFTER the second query has executed.
router.post('/createGroupe/:userId', upload.single('file'), (req, res) => {
let groupe = req.body
// req.body containing the groupe title, description
let userId = req.params.userId
let groupeId
groupe['image'] = req.file
db.query('insert into groupes set ?', groupe, function(err, result){
if (err) throw err;
groupeId = result.insertId.toString()
db.query("insert into groupemembers set ?", [groupeId, userId, 'admin'], function (err, result){
console.log(groupeId)
if (err) return err;
res.send(result.insertId.toString())
})
})
})