I'm using Sequelize
for one project and have already created a Category table, where I store all of my categories in a parent-child relationship. I do know about the package sequelize-hierarchy
, but I wanted to try to find all descendants with a recursive function. So when a receive the categoryId from the client side, I check if it has any children.
const categoryChildren = await db.Category.findAll({attributes:['id'], where: {parent_id: categoryId}});
If it has, then I call a function getDescendants
which has the following declaration:
async function getDescendants (children, storage) {
await children.forEach(async (elem) => {
const hasChildren = await db.category.findAll({attributes:['id'], where:{'parent_id': elem }});
if (hasChildren.length !== 0) {
let ids = [];
hasChildren.forEach( child => { //Transform the response in an array of the elements ID's
ids = [...ids, child.id];
});
storage = [...storage,elem];
return getDescendants(ids, storage);
} else {
storage = [...storage,elem];
return storage;
}
//console.log(storage); //After adding return to getDescendants(ids, storage) this won't run
});
return storage;
}
And I use await because the process will take a while:
const descendants = await getDescendants(children, []);
The console.log
call in my function gets executed and I see my correct ID's after each iteration. However, I receive always an empty array as a result. What I'm doing wrong?