0

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?

CodiClone
  • 141
  • 1
  • 2
  • 8
  • looks like you are missing `return` in front of `getDescendants(ids, storage)` at the recursion. – Emma Feb 24 '21 at 17:18
  • I've tried with it and there is no change – CodiClone Feb 24 '21 at 18:18
  • Could you update your code? also I think `hasChildren` can never been falsely value. `findAll` returns array and in case of no children it will be empty array. `if([])` is true. This still doesn't explain why it is not working though. – Emma Feb 24 '21 at 18:26
  • I've updated it and there is still no change. (have forgot that an empty array is also true...) – CodiClone Feb 24 '21 at 18:41
  • 1
    Async/Await can only work on functions that return a Promise, so you have to wrap your `getDecendants` function in Promise. However, it is still complicated with when to `resolve` because you have `async/await` within `forEach`. – Emma Feb 24 '21 at 19:21
  • This might help https://stackoverflow.com/a/38362312/2956135 – Emma Feb 24 '21 at 19:25
  • Thanks. It's only for the test. The library which the ```Sequelize``` team provides is good and can resolve the problem. Just wanted to test whether I can simplify the problem. – CodiClone Feb 24 '21 at 19:46
  • You are using `async/await` which not works on `foreach` (you can search web, why it not works). Instead, please use `for` loop. – Rahmat Ali Jul 27 '21 at 10:21

0 Answers0