gpt4 book ai didi

javascript - 类型错误 : something is not a function

转载 作者:行者123 更新时间:2023-12-01 01:34:41 25 4
gpt4 key购买 nike

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

我目前正在尝试将用于访问 MySQL 数据库的代码集中在 Express js 服务器中,并希望利用 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()

关于javascript - 类型错误 : something is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52929116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com