I have a MySQL db that contain informations about a survey, including survey compilations by users.
i'm using Express to implement a rest api which retrieve the text of all the questions of the questionnaire.
i'm aving problem with the asynchronous queries. in particular in my code i have a module that retrieve initially all the questions_id of the quest, then insert the result in a array:
allQuestions = [
{
question_id=1,
question_text =""
},
{
question_id=2,
question_text =""
},
]
now i would to iterate in the allQuestions array to retreive the question_text of each question:
const result = allQuestions.map(async (element) =>{
const text = await getQuestionText(element.question_id);
element.question_text = text;
return element
})
and the promise function that run the query and return the result:
function getQuestionText(question_id){
return new Promise((resolve,reject) => {
connection.query('SELECT Q.QuestionText as text FROM question Q WHERE Q.QuestionId='+question_id, (err,rows,fields) => {
if (err) reject(err);
resolve(rows)
});
})
}
now i know that the allQuestion.map now return an array of promises, so i've provided:
Promise.all(result).then(()=>{
res.send(result)
})
so the send method (which send the response of the api) should wait all the promises of the result array, but still i'm getting:
[
{}
]
So there's something wrong with my code, can you please explain what i'm doing wrong?