0

I have a table called categories which should hold the categories of articles available on my site. I want to have a parent and child system in the table, where a category with no parent has the value of 0 for its parent column. A category that has a parent will hold the id of its parent category in its parent column.

To query it I have created this function:

function categoryTree(table, parent = 0) {
    var categTreeArr = [];
    return new Promise(resolve => {
        dbCon.promise().execute("select * from " + table + " where parent = " + parent, []).then(function (err, result, fields) {
            result.forEach(e => {
                var categTreeArrNext = categoryTree(table, e.id).then((value) => {
                    categTreeArr.push([e.img, e.name, e.slug, value]);
                });
            });
            resolve(categTreeArr);
        })
    })
}

On my index page, I have used this code to call the function:

categArr = myModule.categoryTree("course_category", 0).then(value => {
            setValue(row, response, value)
            console.log(value)
});

This gives me an UnhandledPromiseRejectionWarning. Please Help.

PS: I am new to NodeJS. If anything about this question is wrong, please don't flag it. If the question is unclear, I will clarify it in the comment.

1 Answer 1

1

Appearenly, your promise is being rejected and there's not a catch block to handle it. Try catching the whole function and see what is actually going on.

categArr = myModule.categoryTree("course_category", 0).then(value => {
            setValue(row, response, value)
            console.log(value)
}).catch(e => console.log(e));
Sign up to request clarification or add additional context in comments.

1 Comment

I found the other way round - instead of creating a function that queries the database and sorts the result accordingly, I called the mysql2 query inside of the index page and then passing it to a function that sorts it in the form of a parent-child tree. This way I can keep the code simpler and avoid errors. Thanks for the reply though - it will be helpful in the future :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.