-1

How can I retrieve the parameter "results" outside of the function

The result return a json format

Indeed, let users worked but I want use the same thing but now, with the array of results inside the function

Thanks for your help :)

// connect to database
dbConn.connect();

router.use(passport.initialize());
router.use(passport.session());

// Retrieve all users 
router.get('/api/users', (req, res) => {
    dbConn.query('SELECT * FROM users', function (error, results, fields) {
        if (error) throw error;
        return res.json({ data: results });
    });
});

Value of results:

[
  {
    "id": 1,
    "name": "admin",
    "email": "admin@gmail.com",
    "password": "admin"
  },
  {
    "id": 2,
    "name": "emma",
    "email": "emma@gmail.com",
    "password": "password2"
  }
]
Tobias Tengler
  • 6,848
  • 4
  • 20
  • 34
jeremy
  • 165
  • 10
  • 6
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Nicholas Tower Jul 25 '19 at 14:44
  • The code you posted looks like a serverside nodejs application, so why is this tagged [tag:vue.js]? Also, the code appears to be working, what exactly is your problem? You seem to be able to use `results` just fine. – Bergi Jul 25 '19 at 17:59

1 Answers1

-1

Variables declared inside a function will live in that function scope. You need to declare your variable outside, in that way you can use your function to modify its value:

let users = []

router.get('/api/users', (req, res) => {
  dbConn.query('SELECT * FROM users', function (error, results, fields) {
    if (error) throw error;
    res.forEach(result => {
      users.push(result)
    })
  });
});
gianni
  • 1,199
  • 2
  • 14
  • 28
  • While this code snippet may be the solution, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-‌​code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – nircraft Jul 25 '19 at 16:44
  • @nircraft I know guidelines about explaining the reasoning behind answers, but I don't think looping through an array requires further explanation – gianni Jul 25 '19 at 19:58
  • just add some details why OP had the problem and how did you resolve that. It doesn't have to be explaining a for loop – nircraft Jul 25 '19 at 20:07