【问题标题】:Sequelizejs model create callback is not running synchronously?Sequelize 模型创建回调未同步运行?
【发布时间】:2015-02-19 05:59:15
【问题描述】:

我在我的node.js 应用程序中使用SequelizePostgreSQL。我有两个具有一对一关系的表 - CustomersUsers

Customers 表中有外键 UserId。所以,我首先插入Users 表,然后然后 插入Customers,最后插入UserId。这是我的控制器代码:

var self = this;

async.each(data, function(row, callback) {
    var userData = {
        name: row.name,
        /** **/
    }
    // self.User is User model
    self.User.create(userData).then(function(user) {
      console.log("[User.create] succeeded");
      /** **/
      // self.Model is Customer model
      self.Model.create(cusData).then(function(customer) {
          console.log("[Customer.create] succeeded");
          /** **/
      }).catch(function(err) {
          throw err;
      }); // EOL self.Model.create
    }).catch(function(err) {
          throw err;
    }); // EOL self.User.create
    callback();
}, function(err){
    if (err) {
        throw err;
    }
}

我正在使用async.each() 同步循环 2 条记录的数组。当我插入两条记录时,控制台输出为:

[User.create] succeeded
[User.create] succeeded
[Customer.create] succeeded
[Customer.create] succeeded

我的预期是:

[User.create] succeeded
[Customer.create] succeeded
[User.create] succeeded    
[Customer.create] succeeded

我认为这可能是异步编程中同步流的问题。我错了什么?我认为我正确地使用了回调。

【问题讨论】:

  • 你是如何插入两条记录的?您可能会按顺序调用两次,这会在回调有机会触发之前开始两次插入。如果要按顺序完成完整插入,则需要在第一个回调的最后一个回调中开始第二个。
  • @DenisdeBernardy 啊...我使用节点模块Async.js 来循环记录。我更新了问题中的代码。
  • @DenisdeBernardy 可能是callback() 的错误调用?

标签: node.js postgresql asynchronous synchronous sequelize.js


【解决方案1】:

您正在异步启动两个插入操作,因此您无法保证后续查询的顺序。据您所知,根据锁,您可以获得当前或预期的结果。

要强制排序,将迭代从 within 内部回调向前移动:

  self.Model.create(cusData).then(function(customer) {
      console.log("[Customer.create] succeeded");
      /** move the iterator forward here, using e.g. recursion **/
  })

【讨论】:

  • 迭代器正向表示callback()?
  • 不,我的意思是您需要使用适当的迭代器或相当于一个的东西,它可以根据需要产生,或者根据需要锁定,或者逐步推进,例如iter = function(cb, arr, idx) { cb(arr, idx); /* which takes care of calling iter(arr, idx + 1); */ }; 或任何更合适且实际有效的东西。如果您希望强制订购,您当前的代码基本上包含逻辑错误。
  • 或者,不要使用each.async 方法,简单明了,并相应地重新组织您的代码。
  • async.whilst() 确实解决了我的问题。谢谢你。不知道为什么async.each() 不起作用。
猜你喜欢
  • 2014-01-05
  • 2019-08-10
  • 1970-01-01
  • 2020-02-03
  • 1970-01-01
  • 2019-12-12
  • 2020-01-29
  • 1970-01-01
  • 2011-03-08
相关资源
最近更新 更多