-1
I’m developing an application and I’m doing database queries with a predefined model, I’m trying to use an asynchronous function to store the value of this query in a variable. Below follows the code I’m trying to implement:
const Bloco1 = require('../../../models/Bloco1')
var consulta = Bloco1.findOne({ order: [['createdAt', 'desc']] }).then(result => {
return result
}).catch(err => {
console.log(`ERRO: ${err}`)
})
console.log(consulta)
Console return:
Promise [Object] {
_bitField: 0,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_promise0: undefined,
_receiver0: undefined
}
Executing (default): SELECT `Bomba`, `Cisterna`, `Caixa_da_Agua`, `Temperatura`, `Pressao`, `Banco_de_Dados`, `createdAt`, `updatedAt` FROM `bloco1s` AS `bloco1s` ORDER BY `bloco1s`.`createdAt` DESC LIMIT 1;
I gave one console.log(result)
and returned me the following result:
Executing (default): SELECT `Bomba`, `Cisterna`, `Caixa_da_Agua`, `Temperatura`, `Pressao`, `Banco_de_Dados`, `createdAt`, `updatedAt` FROM `bloco1s` AS `bloco1s` ORDER BY `bloco1s`.`createdAt` DESC LIMIT 1;
bloco1s {
dataValues: {
Bomba: 0,
Cisterna: 1,
Caixa_da_Agua: 1,
Temperatura: 22,
Pressao: 15,
Banco_de_Dados: 'sim',
createdAt: 2020-03-03T15:05:09.000Z,
updatedAt: 2020-03-03T15:05:09.000Z
},
_previousDataValues: {
Bomba: 0,
Cisterna: 1,
Caixa_da_Agua: 1,
Temperatura: 22,
Pressao: 15,
Banco_de_Dados: 'sim',
createdAt: 2020-03-03T15:05:09.000Z,
updatedAt: 2020-03-03T15:05:09.000Z
}
How do I save this query in a non-json variable? Can someone help me?
NOTE: I need it this way because I will use it in other places of the application
consulta.then( dados => { use os dados aqui } )
– bfavaretto
sorry @bfavaretto I was not clear at the end of the question, I understood your answer, but this data will change from time to time, so I would like to save this "query" in a variable because I will use in other places
– Teuuz1994
I tried to do it that way and "I think" it worked I did the following:
console.log(consulta.then(dados => { dados: dados }))
– Teuuz1994
You have the option to use asynchronously.
– Lucas Brogni
Because it’s @Lucasbrogni, but I’m terrible with async await or Promisse, my big difficulty is understanding in the code where to expect a return, that’s why I’m stuck on this part, but I really appreciate anyone who can help me understand the problem, I don’t want you to do it for me, I just want to understand to solve
– Teuuz1994