1
I’m trying to return the SELECT
Mysql to make a listing, however, when I give a return
for the function to return the result of the SELECT
, the variable in which I saved this data gets the value undefined
, following example below:
JS:
sqlQuery(dbConnection)
function sqlQuery (dbConnection) {
dbConnection.query('SELECT * FROM printers', function (error, results, fields) {
if (error) return console.log(error)
dbConnection.end()
console.log(results)
})
}
// Neste exemplo, o console.log lista os valores normalmente:
/*
[
RowDataPacket {
ID: 1,
nome: 'Ender 3',
producer: 'Creality'
},
RowDataPacket {
ID: 2,
nome: 'Tarantula',
producer: 'TEVO'
}
]
*/
When I try to return the values of this function and store them in a variable, the following happens:
JS:
const results = sqlQuery(dbConnection)
console.log(results) // undefined
function sqlQuery (dbConnection) {
dbConnection.query('SELECT * FROM printers', function (error, results, fields) {
if (error) return console.log(error)
dbConnection.end()
return results
})
}
How can I fix this?
An observation, thus, when an error occurs will return the error as if it were the expected result, a function
async
returns a promise, which has the methodsthen
when everything happened as expected andcatch
for when an error occurs, as is the error will be returned inthen
, who expects something other than a mistake. Like yourtry catch
only returns the value it should be removed, if you want to, for example, log in the console the error before returning, can keep but cause the exception within thecatch
– Costamilam