0

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?

Fefuzz
  • 21
  • 5
  • `Promise.all` returns a Promise resolving to an array of results, but you aren't using the resolve value. Take and send the `.then` argument instead, in the `Promise.all` – CertainPerformance May 06 '20 at 10:22
  • Thanks, it works with this solution. I didn't quite understand how a Promise.all worked, but with the solution proposed by you i've figured out now! – Fefuzz May 06 '20 at 11:53

0 Answers0