简体   繁体   English

使用module.exports与回调函数导出对象

[英]Export object with module.exports with callback functions

I am trying to learn how to write my own modules for nodejs, specifically to implement various objects, with which I could then work throughout the app. 我正在尝试学习如何为nodejs编写自己的模块,特别是实现各种对象,然后可以在整个应用程序中使用它们。

I want to use result something like this: 我想使用类似这样的结果:

//assuming i have database:
Person_table(ID int A_I, NAME varchar, AGE int)
//code:
var p = new Person("John", 22);
p.writeToDatabase();
//the object is now written in database

I have tried the following, but for some reason beyond my understanding it doesn't work. 我已经尝试了以下方法,但是由于某些我无法理解的原因,它不起作用。 I have declared three files: db.js , person.js , app.js 我已经声明了三个文件:db.js,person.js,app.js

db.js db.js

var mysql = require('mysql');
var conn = mysql.createPool({
    host : 'localhost',
    database: 'db_name',
    user: 'user_name',
    password : 'pass',
    multipleStatement: true,
    connectionLimit : 10
});

conn.getConnection(function(err){
    if(err) throw err;
});

module.exports = conn;

person.js person.js

var db = require('./db.js');

function Person(n, a) {
    this.name = n;
    this.age = a;
}

Person.prototype.writeToDatabase = function (callback) {
    db.query("INSERT INTO Person_table(NAME, AGE) VALUES(?,?)", [this.name, this.age], function (err, rows) {
        if (err) return callback(err);
        else return callback(null, rows);
    });
}

module.exports = Person;

app.js app.js

var Person = require('./person.js')

var p = new Person("John", 22);

p.writeToDatabase(function(err, rows){
    if(err) console.log(err);
    else console.log("written to DB");
});

I would appreciate the help on what is wrong with the code. 对于代码出了什么问题,我将提供帮助。 As a bonus, I would like to ask any good literature on subject of module exporting and object prototypes to create layered nodejs app. 另外,我想问问有关模块导出和对象原型创建分层Node.js应用程序的任何好的文献。

The first advice I'll give is the following, you can use your callback like this in your person.js : 我将给出的第一个建议是,您可以在person.js使用这样的回调:

Person.prototype.writeToDatabase = function (callback) {
    db.query("INSERT INTO Person_table(NAME, AGE) VALUES(?,?)",
      [this.name, this.age],
      callback // Since you do nothing with `err` or `rows`
    );
}

Why ? 为什么呢 Because you handle the callback in your app.js file :). 因为您在app.js文件中处理了回调:)。

Next, I think it doesn't work because you don't wait for your function conn.getConnection to end, and moreover, you don't use the return of this function ! 接下来,我认为它不起作用,因为您不等待函数conn.getConnection结束,而且,您不使用此函数的返回值! Check the documentation here . 此处检查文档。

You should reorganize your code like: 您应该按照以下方式重新组织代码:

db.js db.js

var mysql = require('mysql');

module.exports = mysql.createPool({
    host : 'localhost',
    database: 'db_name',
    user: 'user_name',
    password : 'pass',
    multipleStatement: true,
    connectionLimit : 10
});

person.js person.js

module.exports = function (connection) { // You need the connection to query your database.

    function Person(n, a) {
        this.name = n;
        this.age = a;
    }

    Person.prototype.writeToDatabase = function (callback) {
        // The connection is used here.
        connection.query("INSERT INTO Person_table(NAME, AGE) VALUES(?,?)",
            [this.name, this.age],
            callback
        );
    }

    return Person;
};

app.js app.js

var db = require('./db');

db.getConnection(function (err, connection) { // Once you're connected to the database, you can start using your app.

    var Person = require('./person')(connection); // Since we export a function with a parameter, we need to require the person.js like this.

    var p = new Person("John", 22);

    p.writeToDatabase(function(err, rows) {
        if(err) console.log(err);
        else console.log("written to DB");
    });
});

If I'm not clear, you can ask for more details :). 如果不清楚,您可以询问更多详细信息:)。 If the pattern I show you doesn't fit with your expectation you can do the job in other ways ;) 如果我向您展示的模式与您的期望不符,您可以通过其他方式来完成这项工作;)

I figured out the problem. 我解决了这个问题。 My example is working perfectly, I had just one totally not related problem. 我的示例运行良好,只有一个完全不相关的问题。

At the end of my short program i had process.exit() so that my app would end when it would finish the task. 在我的简短程序结束时,我有了process.exit()这样我的应用程序在完成任务时便会结束。 However I haven't taken into account the asynchronous nature of node.js so, my process.exit() executed before my write to database was completed, therefore it failed. 但是我没有考虑到node.js的异步特性,因此我的process.exit()在对数据库的写操作完成之前就执行了,因此失败了。

Thanks for help anyway! 无论如何,谢谢您的帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM