简体   繁体   中英

node.js setTimeout Loop Issue

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 2times and then 4 etc). Also I'm not sure if its waiting on the database SELECT to completed before trying to process the next time.

Looking for some advise on how to create this loop correctly with node.js

thx

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);
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM