I know this question may already be asked. But I didn't understand how things are worked.that is why I am creating the new thread.
con.query(sql,[req.params.quizId],(err,rows,fields)=>{
//rows contains questions
if(err) throw err;
else{
let object={};
rows.forEach((item,index)=>{
object=item;
//here iam passing question id to get choices a async function
getChoices(item.id)
.then(data=>{
object.choices=data;
//save the question array
response.push(object);
//res.send(response);
});
})
res.send(response) //return empty array
}
});
function getChoices(questionId) {
let sql='SELECT id,text FROM `question_choices` where question_id=?';
return new Promise((resolve, reject) => {
con.query(sql,[questionId],(err,rows,fields)=>{
if(err) throw err;
else {
resolve(rows);
}
})
})
}
I tried several things but none is worked. I think for loop didn't wait for the promise to complete and it sends the response directly. Some async problems are happening there.
I can able to get all questions from database and for each question I need to get corresponding choices that I want.
something like this
[{id:'xx', text:'yy',choices:[{id:'c',text:'kk']},etc]