0
// connections.js
...
module.exports = {
    conn: {
        mongodb: {
            connect: function() {throw ...},
            disconnect: function() {throw ...},
            getState: function() {throw...}
        },
        mysql: {
            connect: function() {throw ...},
            disconnect: function() {throw ...},
            getState: function() {throw ...}
        }
    },
    drivers: {
        mongoose: mongoose,
        mysql: mysql
    },
    states: connectionStates,

    setup: function(config, cb) {
        // provides concrete implementations of connect(), discconnect(),
        // getState(), sets up listeners to relay connection events 
        this.conn.mongodb = setupMongo(config.mongodb); 
        this.conn.mysql = setupSql(config.mysql);
        ...
        cb();
    }
};

现在,如果我将其包括为:

// main.js

var connections = require(__dirname + '/connections'),   
    conn = connections.conn,
    db = conn.mongodb;

// connectionections.setup() not been called yet
exports.foo = function() {
    // connections.setup() already been called before this point
    db.connect(...);            // fails - error thrown - using the abstract function
    conn.mongodb.connect(...);  // works
}

为什么第一个失败?dbvar 应该包含对connections.conn.mongodb? 至少,我希望两者要么工作,要么不工作。允许第一个失败和第二个成功的区别是什么?谢谢

4

1 回答 1

1

它在第一种情况下失败,因为 setup() 在不同的范围内被调用,并且 db/conn.mongodb 在调用 setup 时发生了分歧(写入时有一个副本)。如果你比较 export.foo 函数中的 db 和 conn.mongodb,你应该看到 conn.mongodb 已经被初始化了,setupMongo而 db 仍然有未初始化的版本。不确定调用connections.setup的代码是什么样的,但从这个外观来看,db!=== conn.mongodb。

于 2013-10-23T19:04:57.473 回答