TypeError:某些东西不是函数

问题描述 投票:0回答:1

首先,让我说我对javascript相对较新,这段代码是为了尝试学习新东西,所以即使不是我要求的具体问题,也可以随意评论任何内容。

我目前正在尝试集中我的代码,以便在我的Express js服务器中访问我的MySQL数据库,并希望使用promises。这是我试过的:

let mysql = require('mysql');

    var connectionPool = mysql.createPool({
    host: 'localhost',
    user: 'user',
    password: 'password',
    database: 'database',
    connectionLimit: 10
});

function getConnection() {
    return new Promise(afterConnecting => {
        connectionPool.getConnection((err, connection) => {
            if (err) throw err;
            return afterConnecting(connection);
        });
    });
}

function queryConnection(connection, queryString) {
    return new Promise(consumeRows => {
        connection.query(queryString, function (err, rows) {
            connection.release();
            if (err) throw err;
            return consumeRows(rows);
        });
    });
}

exports.requests = {
    getAllEmployees: function () {
        const queryString = 'SELECT id, name FROM employees;
        return getConnection()
            .then(connection => {
                return queryConnection(connection, queryString);
            });
    }
};

我想这样打电话给getAllEmployees()

var express = require('express');
var router = express.Router();
var db = require('../database');

router.get('/', function (req, res) {
    db.getAllEmployees()
        .then(rows => {
            res.setHeader('Content-Type', 'application/json');
            res.send(JSON.stringify(rows));
        });
});

module.exports = router;

我的问题是我得到一个TypeError,声明“db.getAllEmployees不是一个函数”。调试VS Code时声称db.getAllEmployees确实是一个函数。可能是什么导致了这个?

javascript node.js express
1个回答
2
投票

您将其导出为exports.requests.getAllEmployees因此您必须将其用作:

 db.requests.getAllEmployees()
© www.soinside.com 2019 - 2024. All rights reserved.