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.
data = rows
inside the function will assign the value todata
, 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 thisdata
. 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 thedata
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 thedata
. In this simple example just use thedata
insidequery
– Isac
I just checked, that’s right the function takes a while and my printar code runs before the assignment, thank you
– Lennon S. Bueno