Sami
Sami

Reputation: 6069

Node JS Synchronous database call

I have a problem using Node JS when making synchronous calls.. Here's my problem:

I have the following code:

async.doWhilst(function(callback) {
    //some code
    callback();
}, function() {
    //make a database call and based on the results I should 
    //return true to continue looping or false to stop here
}, function(err) {
   //do some things when the loop finishes
})

The problem is when calling the database it is asynchronous call and the loop continues before even returning the proper value.

Thank you alot for your comments, I have solved the problem by move the database call to the loop code like this:

var results = []
async.doWhilst(function(callback) {
    //some code
    sequelize.query('some query').success(function(result) {
        results = result;
        callback();
    });
}, function() {
    //use the results variable that is fetched from the database
    //return true to continue looping or false to stop here
}, function(err) {
   //do some things when the loop finishes
})

Upvotes: 1

Views: 6648

Answers (4)

Sami
Sami

Reputation: 6069

I have solved the problem by move the database call to the loop code like this:

var results = []
async.doWhilst(function(callback) {
    //some code
    sequelize.query('some query').success(function(result) {
        results = result;
        callback();
    });
}, function() {
    //use the results variable that is fetched from the database
    //return true to continue looping or false to stop here
}, function(err) {
   //do some things when the loop finishes
})

Upvotes: 0

mfrachet
mfrachet

Reputation: 8922

If you really want to use sync call, you can use this library :

https://github.com/luciotato/waitfor

It'll permit you to make sync call using :

var syncDataReceived = wait.forMethod(collection,'insert',{data:toinsert});

Upvotes: 0

Josh Lankford
Josh Lankford

Reputation: 468

You can have Sequelize return once the data has actually returned using this method:

return sequelize
  .query("Database query here")
  .success(function(result) {
      //Do something with result here
      else {
          //Return error
      }
  });

Upvotes: 1

matteo
matteo

Reputation: 1725

Hope the following can help:

(function iterate() {
   executeDatabaseCall(..., function(e,r) {
      if (...conditions to continue looping are verified...)
         iterate();
      else
         ...manage the end of loop...
   });
})();

Upvotes: 0

Related Questions