1

Using MSSQL module, I've been trying to view the create two functions, primarily one to read the data off the database table and make it into a variable. The other will write data from an get request and update the database table.

I have the following for reading the data but I do not get any response once logged in, unsure what I'm doing wrong.

let id = {};
let date = {};
let response = {};

let readLoggerData = function(err) {
  if (err) throw err;
  con.query('SELECT * FROM Logging ORDER BY Date DESC;'),
    function(id, response, date) {
      if (response) {
        id = request.query('SELECT TOP 1 id from Logging;');
        date = request.query('SELECT TOP 1 Date FROM Logging;');
        response = request.query('SELECT TOP 1 Response from Logging;');
      };
    };
};
console.log(id);
});

1 Answer 1

1

When you call something asynchronous, you need to wait for it to be done. Your console.log() gets called immediately after the code runs, but the con.query() might take a couple of seconds.

To solve it: Move the console.log() into the function() part of the con.query() function to fix your problem. I've also allowed myself to rewrite it a bit, so it uses ES6 syntax (basically just removing the functions). You should consider doing that in the future.

let id = {};
let date = {};
let response = {};

let readLoggerData = err => {
    if (err) throw err;
    con.query('SELECT * FROM Logging ORDER BY Date DESC;'),
        (id, response, date) => {
            if (response) {
                id = request.query('SELECT TOP 1 id from Logging;');
                date = request.query('SELECT TOP 1 Date FROM Logging;');
                response = request.query('SELECT TOP 1 Response from Logging;');

                console.log(id);
            };
        };
};

Oh and you have a syntax error as well. The last ) is invalid.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for this! I'm still getting a hang of the async functions and really appreciate the insight.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.