It's my first project using NodeJS, and I'm trying to fetch all posts in all groups in which the user is a member. And as such, I'm trying to put all the data into and array before calling the res.send method. However, the array is empty at the end (pardon the naming of tables as I used french).
router.get('/getUserPostes/:userId', async (req, res) => {
let userId = req.params.userId;
let endResult = []
await db.query('select groupeId from groupemembers where userId = ?', userId, async function(err, result){
if (err){
console.log(err.message)
res.send(null)
}
else {
await result.map(async groupe => {
await db.query('select * from postes where groupeId = ?', groupe.groupeId, function(err, result){
if (result != []){
endResult.push(result)
}
})
})
res.send(endResult)
}
})
})
await result.map()does not do what you want because you're awaiting an array (since.map()return an array) not a promise. You could doawait Promise.all(result.map(...))await db.query()also does not do anything useful because you're also passing a callback. If you pass a callback, then it does NOT return a promise. Please don't just go cramming anawaiteverywhere without understanding how you're precisely awaiting a promise since that's the only thing it is useful toawait.