How to increment an external variable to a callback in Nodejs?

Asked

Viewed 49 times

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?

  • Returns no error, just not to increment. It does not understand as a variable that is part of the scope.

  • 1

    You are treating asynchronous code as synchronous, which is a "silent" error. Try to understand what a callback javascript...

  • 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?.

  • 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...

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.