Sithu
Sithu

Reputation: 4862

Sequelizejs model create callback is not running synchronously?

I'm using Sequelize and PostgreSQL in my node.js application. I have two tables with one-to-one relationship - Customers and Users.

There is foreign key UserId in the Customers table. So, I firstly insert into the Users table and then insert into the Customers with the last inserted UserId. Here is my controller code:

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

I'm using async.each() to loop the array of 2 records synchronously. When I inserted the two records, the console output is:

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

What I expected is:

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

I think it could be a problem of synchronous flow in asynchronous programming. What am I wrong? I think I'm using the callbacks correctly.

Upvotes: 0

Views: 1335

Answers (1)

Denis de Bernardy
Denis de Bernardy

Reputation: 78473

You're initiating the two inserts asynchronously, so you've no guarantee on the order of the follow-up queries. For all you know, depending on locks, you could get the current or your expected result.

To force the order, move the iteration forward from within the inner callback:

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

Upvotes: 1

Related Questions