I've been turning in circle searching for an answer to this for 2 days now so any help to guide me in the right direction would be appreciated.
I am building a server side app that will query data from a Database un MsSql every x time and return the data to the various clients through sockets.
The part I'm having an issue with is the first one. What I want to achieve is simple, I want to fetch the data from the DB and then store it in a variable accessible to other function so that my app can update the different clients with the right information everytime. I don't want to query the DB each and every single time as this wouldn't be very efficient or scalable.
I know I need to use callback but I'm unsure why it doesn't work and I'm pretty I'm missing some knowledge about this.
The code that's definitly producing the data:
const GetDataset = async (queryStr, callback) => {
const pool = await poolPromise;
const result = await pool.request().query(queryStr);
console.log(result);
}
I know that I needed to make those calls async with the mssql promise stuff. But then I need the content of result (The recordset), to be returned back to a function within setInterval so I can store it into my variable.
Here's my non-working code that I lastly tried. I've tried so many combination I can't list them all. None of them were returning the result to a variable but just printing to console... which obviously works.
const BotListUpdate = (data) => {botList = data}
const GetDataset = async (queryStr, callback) => {
const pool = await poolPromise;
const result = await pool.request().query(queryStr);
callback(result.recordset);
}
setInterval(() => {
GetDataset('SELECT * FROM [MachinesInfo];', BotListUpdate);
console.log(botList);
}, 5000);
I tried to put the function directly in the call:
GetDataset('SELECT * FROM [MachinesInfo];', (data) => {botList = data});
I'm out of imagination at this point.
Thanks.
Resolved with promise as suggested:
const BotListUpdate = (data) => {botList = data}
const GetDataset = async (queryStr) => {
const pool = await poolPromise;
const result = await pool.request().query(queryStr);
return result.recordset;
}
setInterval(() => {
GetDataset('SELECT * FROM [MachinesInfo];').then((recordset) => botList = recordset);
console.log(botList);
}, 5000);