【问题标题】:Node JS Synchronous database callNode JS 同步数据库调用
【发布时间】:2015-01-06 11:49:00
【问题描述】:

我在使用 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
})

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

非常感谢您的 cmets,我已经通过将数据库调用移动到循环代码来解决问题,如下所示:

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

【问题讨论】:

  • 测试函数应该是同步的,尝试在其中引入异步代码和某种等待循环会真的,真的,真的不好
  • 我试图让它同步,但我不知道如何,问题是数据库调用取决于循环代码中的变量更改
  • 您不能使异步操作同步运行。你就是不能。它与同步操作的时间不同,无法做到。
  • 非常感谢@JanAagaardMeier,您的评论给了我将数据库调用移至循环代码的提示。我将正确回答我所做的事情。

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


【解决方案1】:

我已经通过将数据库调用移动到循环代码来解决问题,如下所示:

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

【讨论】:

  • 这不是同步数据库调用。
【解决方案2】:

如果你真的想使用同步调用,你可以使用这个库:

https://github.com/luciotato/waitfor

它将允许您使用以下方式进行同步呼叫:

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

      希望以下内容能有所帮助:

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

      【讨论】:

        猜你喜欢
        • 2017-02-03
        • 2013-03-12
        • 2018-08-27
        • 1970-01-01
        • 2022-06-14
        • 1970-01-01
        • 2016-07-25
        • 2017-12-09
        • 2018-10-27
        相关资源
        最近更新 更多