节点JS同步数据库调用

时间:2014-11-10 08:09:18

标签: node.js asynchronous sequelize.js async.js

在进行同步调用时我遇到使用Node JS的问题。这是我的问题:

我有以下代码:

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

问题是当调用数据库时它是异步调用,并且循环在继续返回正确的值之前继续。

非常感谢您的评论,我通过将数据库调用移动到这样的循环代码来解决问题:

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

4 个答案:

答案 0 :(得分:1)

使用此方法实际返回数据后,您可以返回Sequelize:

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

答案 1 :(得分:0)

希望以下内容可以提供帮助:

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

答案 2 :(得分:0)

如果您真的想使用同步通话,可以使用此库:

https://github.com/luciotato/waitfor

它允许您使用以下方式进行同步通话:

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

答案 3 :(得分:0)

我已经通过将数据库调用移动到这样的循环代码来解决了这个问题:

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