【发布时间】:2012-05-19 23:17:27
【问题描述】:
我正在使用 Node.js ORM 模块:https://github.com/dresende/node-orm
我可以通过这样做来创建模型:
var orm = require("orm");
var db = orm.connect("creds", function (success, db) {
if (!success) {
console.log("Could not connect to database!");
return;
}
var Person = db.define("person", {
"name" : { "type": "string" },
"surname": { "type": "string", "default": "" },
"age" : { "type": "int" }
});
});
问题是我想将 Person(以及所有其他模型)放在外部包含中。
如果我这样做:
require("./models/person.js");
我不能在其中使用 db 变量,因为它只存在于 orm.connect() 的回调函数的上下文中。我无法将 orm.connect 移动到 require (person.js) 并为模型信息执行 module.export,因为在父脚本中,require 会发生,然后模型将不会在下一行准备好,因为它不等待回调。浏览器
//person.js
// db and orm get defined up here as before
Person = {}; // code from above, with the define and etc.
Module.exports = Person;
//app.js
person = require("./models/person.js");
console.log(person); // returns undefined, connect callback isn't done yet
我觉得有一种明显的方法可以做到这一点。
【问题讨论】: