I'm making a recursive async function that's running a mysql query. This is the db I'm working with:
+----+-------------------+-----------+----------+-----------+---------------------+
| id | task | completed | parentid | createdby | createdat |
+----+-------------------+-----------+----------+-----------+---------------------+
| 1 | Clean apartment | 0 | NULL | 1 | 2022-03-24 00:47:33 |
| 2 | Clean bathroom | 0 | 1 | 1 | 2022-03-24 00:47:33 |
| 3 | Clean kitchen | 0 | 1 | 1 | 2022-03-24 00:47:33 |
| 4 | Wash shower | 0 | 2 | 1 | 2022-03-24 00:47:33 |
| 5 | Wash toilet | 0 | 2 | 1 | 2022-03-24 00:47:33 |
| 6 | Clean glass panes | 1 | 4 | 1 | 2022-03-24 00:47:33 |
| 7 | Clean faucet | 0 | 4 | 1 | 2022-03-24 00:47:33 |
| 8 | Clean sink | 0 | 3 | 1 | 2022-03-24 00:47:33 |
| 9 | Take out trash | 1 | 3 | 1 | 2022-03-24 00:47:33 |
+----+-------------------+-----------+----------+-----------+---------------------+
If I had this db stored in an array I could run this function:
function comp(tasks, taskId) {
var task = tasks.find(task => task.id === taskId)
var children = tasks.filter(t => t.parentId === taskId)
task.children = children.map(child => comp(tasks, child.id));
return task
}
to recursively nest the child task into the main task.
The problem now is that I don't have a good understanding of async functions.
This is how far I've gotten now:
async function comp(taskId) {
// SELECT * FROM tasks WHERE id = taskId
var task = await con.promise().query('select * from tasks where id = ' + taskId)
// SELECT * FROM tasks WHERE parentId = taskId
var children = await con.promise().query('select * from tasks where parentid = ' + taskId)
task[0][0].children = children[0].map(child => {
comp(child.id)
})
console.log(task[0])
}
But this returns the task with undefined children:
[
{
id: 1,
task: 'Clean apartment',
completed: 0,
parentid: null,
createdby: 1,
createdat: 2022-03-23T23:47:33.000Z,
children: [ undefined, undefined ]
}
]
In short, the result I'm looking for would look like this:
{
id: 1,
task: 'Clean apartment',
completed: 0,
parentid: null,
createdby: 1,
createdat: 2022-03-23T23:47:33.000Z,
children: [
{
id: 2,
task: 'Clean bathroom',
completed: 0,
parentid: 1,
createdby: 1,
createdat: 2022-03-23T23:47:33.000Z,
children: [
{
id: 4,
task: 'Wash shower',
completed: 0,
parentid: 2,
createdby: 1,
createdat: 2022-03-23T23:47:33.000Z,
children: [ ... ]
},
{
id: 5,
task: 'Wash toilet',
completed: 0,
parentid: 2,
createdby: 1,
createdat: 2022-03-23T23:47:33.000Z,
children: [ ... ]
},
]
},
{
id: 3,
task: 'Clean kitchen',
completed: 0,
parentid: 1,
createdby: 1,
createdat: 2022-03-23T23:47:33.000Z,
children: [ ... ]
},
}
Any tips?