β

Answer by zangw for How do you make sure while wor

User zangw - Stack Overflow 120 阅读

How does mongoose make sure the code at line B is executed after line A finished and succeeded?

You may misunderstand it, it does NOT means the line A is succeeded.

Per mongoose.connect source code ,

Mongoose.prototype.connect = function() {
  var conn = this.connection;
  if (rgxReplSet.test(arguments[0]) || checkReplicaSetInUri(arguments[0])) {
    return new MongooseThenable(this, conn.openSet.apply(conn, arguments));
  }
  return new MongooseThenable(this, conn.open.apply(conn, arguments));
};

The MongooseThenable is returned, and after mongoose.connect() is called, it call open to create connection, and check the connection is successful or failed through event connected or error , so it could better to save data into db in the callback of connected event.

mongoose.connection.on('error', function() {
    console.log('Could not connect to mongoDB');
});
mongoose.connection.on('connected', function() {
    console.log('Establish connection to mongoDB');
    kitty.save(function(err) { //(B)
      if (err) // ...
        console.log('meow');
    });
});
作者:User zangw - Stack Overflow
most recent 30 from stackoverflow.com
原文地址:Answer by zangw for How do you make sure while wor, 感谢原作者分享。

发表评论