本文介绍了使用"require"处理Node.js异步返回(节点ORM)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Node.js ORM模块: https://github.com/dresende/node -orm

I'm using the Node.js ORM module : https://github.com/dresende/node-orm

我可以通过以下方式创建模型:

I'm able to create a model by doing this:

    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(以及与此相关的所有其他模型)放在外部包含中.

The problem is that I want to put Person (and all other models for that matter) in external includes.

如果我做这样的事情:

   require("./models/person.js");

我不能在其中使用db变量,因为它仅存在于orm.connect()的回调函数的上下文中.我无法将orm.connect移至require(person.js)并为模型信息执行module.export,因为在父脚本中,将发生require,然后下一行将无法准备好模型,因为它没有等待回调. IE浏览器

I can't use the db variable inside of that, because it only exists in the context of the callback function for orm.connect(). I can't move orm.connect to the require (person.js) and do a module.export for the model info, because in the parent script, the require will happen and then the model won't be ready by the next line, since it's not waiting on the callback. IE

//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

我觉得有一个明显的方法可以做到这一点.

I feel like there's an obvious way to do this.

推荐答案

也许可以使person.js的导出成为函数,然后传递db?像这样:

Perhaps could make the person.js's export into a function, and pass in db? Like this:

//app.js
var orm = require("orm");
var db = orm.connect("creds", function (success, db) {
    if (!success) {
        console.log("Could not connect to database!");
        return;
    }

  var Person = require("./models/person.js")(db);
});

//person.js
module.exports = function(db){
    return db.define("person", {
        "name"   : { "type": "string" },
        "surname": { "type": "string", "default": "" },
        "age"    : { "type": "int" }
    });
}

这篇关于使用"require"处理Node.js异步返回(节点ORM)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 05:37