首页 > 解决方案 > TypeError:某事不是函数

问题描述

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

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

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确实是一个函数。这可能是什么原因造成的?

标签: javascriptnode.jsexpress

解决方案


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

 db.requests.getAllEmployees()

推荐阅读