将callack的值绑定到实例nodejs的属性

时间:2018-08-08 03:39:16

标签: javascript jquery node.js asynchronous callback

我想永久存储回调函数的结果,这是代码:

class constants {
    constructor(){
       this.acquire()
    }

    acquire() {
       this.last_refresh = new Date().getDate();
        require('./db_slave').then(conn => {
            return conn.query("SELECT table_name FROM information_schema.tables where table_schema='gen'").then(result => {
                this.tables = result
                console.log(result)
            });
        }).catch(err => {
            // handle error here
        });
    }

    tables() {
        this.refresh()
        return this.tables
    }
    refresh() { if (new Date().getDate() != this.last_refresh) this.acquire() }
}

module.exports = constants

但这显然不起作用,因为this.tables = result什么也没做...

以下是此承诺正在调用的文件:

var mysql = require('promise-mysql');
var db = require('./db')

module.exports = mysql.createConnection({
    host: db.host,
    user: db.user,
    password: db.password
}).then(conn => {
    console.log("connected to the DB");
    return conn;
}).catch(err => {
    console.log("error connecting to the DB", err);
    throw err;
});

我如何将结果永久存储在该回调中?

这是我的用法:

var db_constants = require('./database_service/db_constants')

let cons = new db_constants()

console.log(cons.tables())

0 个答案:

没有答案