0

Node.js のオブジェクト属性に問題があります。テストオブジェクトでは属性が期待どおりに設定されていますが、articleオブジェクトでは同じことが機能しません。私が見る違いは、アーティクルの関数が非同期で呼び出されることです。私は少し道に迷っていることを告白しなければなりません...

testオブジェクトとarticle オブジェクトをインスタンス化するapp.jsを次に示します

/**
 *  Load express.
 */
var express = require('express');
var app = express();

/**
 *  Load articles.
 */
var articles = require('./article.js');
var l_articles = new articles.Articles();

var test = require('./test.js');
var l_test = new test.Test();

app.get('/', function (req, res) {
    console.log(l_test.get());
    l_test.set('it is', 'midnight');
    console.log(l_test.get());

    articles.Articles.get(1);

    res.send('OK');
})

app.listen(3001, function () {
    console.log(l_test.get());
    l_test.set('goodbye', 'sunshine');
    console.log(l_test.get());

})

ここに私のかなり単純な test.js があります:

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

function Test() {
    this.timestamp = new Date();
    console.log(this.timestamp);
    this.attribute1 = 'hello';
    this.attribute2 = 'world';
}

Test.prototype.get = function() {
    console.log(this.timestamp);
    return (this.attribute1 + ' ' + this.attribute2);
}

Test.prototype.set = function(p_param1, p_param2) {
    console.log(this.timestamp);
    this.attribute1 = p_param1;
    this.attribute2 = p_param2;
}

module.exports = {
    Test: Test
};

ここに私のかなり単純な article.js があります:

var sqlite3 = require('sqlite3').verbose();
var app = require('./app.js');

function Articles(p_id) {
    this.timestamp = new Date();
    console.log(this.timestamp);
    this.db = new sqlite3.Database('./gescom.sqlite');
    if (p_id == undefined) {
        this.db.all('SELECT * FROM T_ARTICLE', this.load);
    } else {
        this.db.all('SELECT * FROM T_ARTICLE WHERE id = ' & p_id, this.load);
    }
}

Articles.prototype.load = function(p_err, p_rows) {
    console.log(this.timestamp);
    var ids = [];
    var articles = [];
    p_rows.forEach(function(p_row) {
        ids.push(p_row.ID);
        articles.push([p_row.ID, p_row.SHORT_NAME]);
    });
    this.ids = ids;
    this.articles = articles;
    console.log(this.ids.length + ' articles loaded from database.');
}

Articles.prototype.get = function (p_id) {
    console.log(this.timestamp);
    var l_return;
    if ((this.ids == undefined) || (this.articles == undefined)) {
        console.log('No articles loaded from database.');
    } else {
        console.log(this.ids.length + ' articles loaded from database.');
        if (p_id == undefined) {
            l_return = this.articles;
        } else {
            if (this.ids.indexOf(p_id) != undefined) {
                l_return = (this.articles[this.ids.indexOf(p_id)]);
            } else {
                l_return = undefined;
            }
        }
    }
    return l_return;
}

module.exports = {
    Articles: Articles
};
4

0 に答える 0