I have data that I received from mysql. These are tests, I received all the questions and I need to drive them into the array to get all the values ​​obtained from the sample. And I want to move all the answers to an array. To show it all

const Router = require('koa-router'), Test = require('./model/test'), router = new Router(); router.get('/testing/:id', async ctx => { let theme = await Test.theme(ctx.params.id); let test = await Test.test(ctx.params.id); let answearArr = test.map(item => { Test.answear(item.id); }); console.log(answearArr); }) 

I get an array like this [undefined, undefined, undefined] Inside the item is the next array

 RowDataPacket { id: 1, name: 'Первый вопрос', id_theme: 1 } RowDataPacket { id: 2, name: 'Второй вопрос?', id_theme: 1 } RowDataPacket { id: 4, name: 'Третий вопрос', id_theme: 1 } 

To understand what is in the variable

 const db = require('../bin/db'); let Test = { test: function(id){ return requestTest('SELECT * FROM questions WHERE id_theme = ?', id); }, answear: function(id){ return requestTest('SELECT * FROM answers WHERE id_question = ?', id); }, theme: function(id){ return requestTest('SELECT name FROM thema WHERE id = ?', id); } }; function requestTest(sql, req) { return new Promise((resolve, reject) => { db.query( sql, [req], (err, rows) => { if(err) reject(err); resolve(rows); }); }).then(rows => {return rows;}); } module.exports = Test; 

  • Is this probably a node.js thread? you have asynchronous methods, data is added to the array before the answer comes. the others are called with await , and the answers are without. In any case, it is not good to draw answers to each question by a separate request. - teran
  • you return all the answers for the whole test with a pack, and then shove what-where. - teran
  • She also returns a pack of all questions, on a specific id. In the answer there, the answer is simply stored in the answer itself or not. That is, the usual notation 1 or 0. I learned that item.id does not work, this array comes in value, and accordingly this request expects one value and gets an array - Ruslan

1 answer 1

 router.get('/testing/:id', async ctx => { let theme = await Test.theme(ctx.params.id); let test = await Test.test(ctx.params.id); let answearArr = await Promise.all(test.map(item => { return Test.answear(item.id); })).then(id => id); console.log(answearArr); await ctx.render('test', { title: 'Тест', path: 'test', }) }) 

 answear: function(id){ return new Promise((resolve, reject) => { db.query( `SELECT * FROM answers WHERE id_question IN (?)`, id, (err, rows) => { if(err) reject(err); resolve(rows); }); }).then(rows => {return rows;}); },