How to assign the result of Connection.query to a global variable?

Asked

Viewed 83 times

0

I’m learning to use the module mysql and I came across a situation of not being able to assign the result to a global variable, follow my code:

let data = 0

  connection.query(query, (err, rows, fields) => {
    if (err) {
      console.log('An error ocurred performing the query.')
      console.log(err)
      return
    }

    data = rows
  })

if I print the variable data the result is zero, as I attribute the result to her?

Obs: I used this example of documentation.

  • 1

    data = rows inside the function will assign the value to data, but it is important to keep in mind that this is an asynchronous function. So it may not work, depending on where and how you use this data. Compose example, this query can hypothetically take say 5 seconds to run, and meanwhile the rest of the file has already been processed and so already used the data without being assigned. As a general rule the solution you want is another but it is difficult to help without seeing how you are using the data. In this simple example just use the data inside query

  • I just checked, that’s right the function takes a while and my printar code runs before the assignment, thank you

No answers

Browser other questions tagged

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