During a POST request I’m trying to insert quiz related data into 2 tables: questions & choices and also to return the saved data. This is how data looks like:
{
"id": 2,
"title": "Practice #1",
"category_id": 2,
"quizQuestions": [
{
"id": 4,
"time": 180,
"points": 10,
"question": {
"id": 13,
"choices": [
{
"id": 55,
"is_correct": false
},
{
"id": 57,
"is_correct": false
},
{
"id": 56,
"is_correct": false
},
]
}
},
...
]
}
This is the code for parsing the data and executing the inserts:
async processUserQuizQuestions(userQuizId, questionsRaw) {
const savedQuestions = Promise.all(
questionsRaw.map(async (question, idx) => {
const choicesRaw = question.question.choices;
const savedQuestion = await UserQuestion.create({
uq_id: userQuizId,
question_id: question.question.id,
display_order: idx + 1,
});
const savedChoices = Promise.all(
choicesRaw.map(async (choice, idx) => {
const savedChoice = await UserChoice.create({
uqq_id: userQuestionId,
choice_id: choice.id,
iteration: Utils.letters()[idx],
});
return savedChoice;
);
return { ...savedQuestion, choices: savedChoices };
}),
);
return savedQuestions;
},
The data, both questions and choices, is inserted as expected in the database, but the returning value doesn’t contain the choices:
{[
{
"answer_id": 0,
"id": 83,
"uq_id": 17,
"question_id": 13,
"display_order": 1,
"updatedAt": "2022-02-02T17:17:25.954Z",
"createdAt": "2022-02-02T17:17:25.954Z",
"answer": null,
"choices": {}
},
...
]}
I assume that there must be something wrong with the nested Promise.all and the array.map because the code doesn’t wait for choices processing.
I don’t think the environment matters but this is an Express server on Node JS with Sequelize and Postgres.