Adr*_*oly 10 model-view-controller design-patterns asynchronous mongodb node.js
由于MongoDB数据库访问和初始化在Node.js上是异步的,我想在db初始化之后为每个集合定义一个导出包装db调用的模块.
这样的"Cars.model.js"模块看起来像这样:
var db = require("mongodb");
db.collection("cars", function(err, col) {
exports.getCars = function(callback) {
col.find({}, callback);
};
});
Run Code Online (Sandbox Code Playgroud)
以便其他模块可以运行:
var carModel = require("Cars.model.js").getCars;
getCars(err, cars) {
// (do something with cars here...)
};
Run Code Online (Sandbox Code Playgroud)
它发生在我身上getCars是未定义的,因为我的第二个模块运行时数据库访问尚未初始化.
你如何处理创建这种异步数据库模型?
Ray*_*nos 11
exports在您离开文件后,您无法写信.你必须阻止.为了避免阻塞,我会使用延迟加载资源.
var carCol;
var carEmitter = new require("events").EventEmitter;
exports.getCars = function(callback) {
// if no car collection then bind to event
if (carCol === undefined) {
carEmitter.on("cars-ready", function() {
callback(carCol);
});
} else {
// we have cars, send them back
callback(carCol);
}
}
db.collection("cars", function(err, col) {
// store cars
carCol = col;
// tell waiters that we have cars.
carEmitter.emit("cars-ready");
});
Run Code Online (Sandbox Code Playgroud)
使用事件发射器来模拟延迟加载.您可能希望概括为LazyLoadedCollection类/对象以使代码更整洁/更干.
| 归档时间: |
|
| 查看次数: |
3806 次 |
| 最近记录: |