Adam
Adam

Reputation: 20882

Node.js Async Loop to Query Database

I'm new to node.js.

I'm building a loop to query a database with chat messages every 3 seconds to then send required new messages to required users.

This is the loop I have - but currently it only loops once:

  // New Database Chat Messages Send
  var newDBMessagesInterval = 3000;     // 3 Seconds
  (function newDBMessagesSchedule() {
    setTimeout(function() {
      async(function() {
        console.log('async is done!');
        newDBMessagesSchedule();
      });
    }, newDBMessagesInterval)
  })();





function async() {
  console.log('in async function....');
}

Do I need to return something from the async function for the loop to continue?

Also is this a good/bad way to do a loop - my intention is to put a DB SELECT into the async function and don't what the DB calls to overlap.

Also is this non-blocking?

thx

Upvotes: 0

Views: 863

Answers (1)

Aaron Dufour
Aaron Dufour

Reputation: 17505

There is nothing magical about aynchronous functions. You have to call the callback to an asynchronous function at some point. For testing purposes you should change async to:

function async(callback) {
  callback();
}

Yes, this is non-blocking.

However, from your comment, I see that you're doing this to send messages to sockets. This isn't a great way to do that. You should look into getting a "pub/sub" system, and having each server subscribe and publish their own messages. Redis is a good choice for this.

Upvotes: 4

Related Questions