javascript - 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
确实是一个函数。这可能是什么原因造成的?
解决方案
您将其导出,exports.requests.getAllEmployees
因此您必须将其用作:
db.requests.getAllEmployees()
推荐阅读
- nginx - FreeBSD 11.1 上的 Nginx 乘客
- python - 如何仅使用带有歌曲名称的 python 从 YouTube 流式传输 mp3 音频
- ruby-on-rails - searchkick 的自定义批量索引器:映射选项被忽略
- c# - 在 Crystal Report 中显示格式化的所见即所得字段
- html - Flexbox:连续包装时,如何在没有额外标记的情况下堆叠两个以上的元素?
- gcc - 我怎样才能找到哪个指令使我的程序因非法指令错误而崩溃?
- c# - 在实时脚本c#编译器中引入依赖
- php - 为什么 Cron 作业忽略使用 init_set 指定的超时?
- azure - 是否可以将证书信息从密钥凭据使用/转发到不记名令牌(Azure AD)
- c# - 如何使用对象列表填充网格?在c#中