0
Hello!
I want to increment the hierarchy variable, but I can’t do it.
Can someone help me?
function getHierarquia(id, req, res) {
var hierarquia = "";
res.locals.connection.query('SELECT id, owner_id FROM users WHERE owner_id = ?', [id], function (error, results, fields) {
if (error) {} else {
results.forEach(element => {
hierarquia += "," + getHierarquia(element['id'], req, res)
});
}
})
return hierarquia
}
Which error message returned?
– Dakota
Returns no error, just not to increment. It does not understand as a variable that is part of the scope.
– Gustavo Bretas
You are treating asynchronous code as synchronous, which is a "silent" error. Try to understand what a callback javascript...
– Luiz Felipe
Your case is of callback, but promises can be used to explain why you can’t do this kind of thing too. See more on: How to assign a Promise result to a variable?.
– Luiz Felipe
As you are trying to increment it within the query callback, within this callback the hierarchy has no reference at all. You can place the query inside a precedent in another function, and from the return of it handle the hierarchy. I have not tested here, but it may be possible to use "bind" in your query method to include the hierarchy reference in it...
– Marcos Alberto Cosmoski Filho