0

I'm new to Node.js.

I have tried to create a setTimeout that executes a database SELECT query and repeats 3 seconds after processing the SELECT results has completed.

  var newDBMessagesInterval = 3000;     // 3 Seconds
  (function newDBMessagesSchedule() {
    setTimeout(function() {
      dbNewMessagesQuery(function(dbResults,dbResultsLength) {

        console.log(dbResults);

        newDBMessagesSchedule();
      });
    }, newDBMessagesInterval)
  })();

function dbNewMessagesQuery(callback) {
  dbConnection.query("SELECT data1,data2,data3 FROM table WHERE condition=1;", function (dbError, dbResults, dbFields) {
    if(dbResults.length > 0) {
      callback(dbResults,dbResults.length);
    }
  });
  callback();
}

It appears the setTimeout number of loops increases each time it runs (eg: first one console.log(dbResults), but then 2 times and then 4 etc). Also I'm not sure if it's waiting on the database SELECT to completed before trying to process the next time.

How can I create this loop correctly?

1 Answer 1

2

Your dbNewMessagesQuery calls callback twice. Once synchronously, and once after the db query succeeds. You should just be calling it once after the query is done. With your current code, for every call to newDBMessagesSchedule, you queue up two more calls to run later.

function dbNewMessagesQuery(callback) {
  dbConnection.query("SELECT data1,data2,data3 FROM table WHERE condition=1;", function (dbError, dbResults, dbFields) {
    callback(dbResults, dbResults.length);
  });
}

I'd also recommend not bothering to pass the length separately, and instead pass along the error if there is one. Currently you just assume there will never be an error.

function dbNewMessagesQuery(callback) {
  dbConnection.query("SELECT data1,data2,data3 FROM table WHERE condition=1;", function (dbError, dbResults, dbFields) {
    callback(dbError, dbResults);
  });
}
Sign up to request clarification or add additional context in comments.

Comments

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.