【发布时间】:2020-05-02 01:55:37
【问题描述】:
我是如何在 nodejs 中使用 mysql 的初学者
所以我在 youtube 上尝试了这个基本教程并开始调整它
我正在尝试使用 async/await,以便可以在 mysql 中开始事务
这是代码
const pool = require('../../config/database')
module.exports = {
create: async (data, callBack) => {
const connection = await pool.getConnection();
await connection.beginTransaction();
try {
await connection.query(
`insert into user_details(fullname,gender,email,password,phone_number)
values(?,?,?,?,?)`,
[
data.fullName,
data.gender,
data.email,
data.password,
data.phone_number
],
(error, results, fields) =>{
if(error){
return callBack(error);
}
return callBack(null, results);
}
);
await connection.commit();
} finally {
connection.release();
}
}
}
但问题是 连接 未定义
我在const connection = await pool.getConnection(); 行之前安慰了池,它不为空。
但是在const connection = await pool.getConnection(); connection 之后是未定义的
有什么帮助吗? :D
编辑: 致@Terry Lennox
这是日志
addUserDetails, creating connection...
addUserDetails, creating connection...
addUserDetails, starting transaction...
addUserDetails, running query...
addUserDetails, an error occurred: TypeError: Cannot read property 'fullName' of undefined
at Object.addUserDetails [as create] (C:\Playground\nodejs-mysql\api\users\user.service.js:19:26)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:12412) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'fullName' of undefined
at Object.addUserDetails [as create] (C:\Playground\nodejs-mysql\api\users\user.service.js:19:26)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:12412) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:12412) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
addUserDetails, starting transaction...
addUserDetails, running query...
addUserDetails, committing transaction...
addUserDetails, transaction committed.
编辑:
这是我的 app.js
require('dotenv').config();
const express = require('express');
const app = express();
const userRouter = require('./api/users/user.router');
app.use(express.json());
app.use('/api/users', userRouter);
app.listen(process.env.PORT, ()=>{
console.log("Server is now running");
})
这是我的 user.router.js
const userController = require('./user.controller')
const router = require('express').Router();
const {checkToken} = require('../../auth/token.validation');
router.post("/", userController.createUser);
router.get("/", checkToken, userController.getUsers);
router.get("/:id", checkToken, userController.getUserById);
router.patch("/", checkToken, userController.updateUser);
router.delete("/:id", checkToken, userController.deleteUser);
router.post("/login", userController.login)
module.exports = router;
这是我的控制器
const userService = require('./user.service');
const { genSaltSync, hashSync, compareSync} = require('bcryptjs');
const { sign } = require('jsonwebtoken');
module.exports = {
createUser: (req,res) =>{
const body = req.body;
const salt = genSaltSync(10);
body.password = hashSync(body.password, salt);
userService.create()
userService.create(body, (err, results)=>{
if(err){
console.log(err);
return res.status(500).json({
success: 0,
message: "An error occured: "+ err
})
}
return res.status(200).json({
success: 1,
code: results,
data: body
});
})
}
}
最后是我的 service.js
async function addUserDetails(data) {
console.log("addUserDetails, creating connection...");
const connection = await pool.getConnection();
try {
console.log("addUserDetails, starting transaction...");
await connection.beginTransaction();
console.log("addUserDetails, running query...");
const queryResult = await connection.query(
`insert into user_details(fullname,gender,email,password,phone_number) values(?,?,?,?,?)`,
[
data.fullName,
data.gender,
data.email,
data.password,
data.phone_number
]
);
console.log("addUserDetails, committing transaction...");
await connection.commit();
console.log("addUserDetails, transaction committed.");
return queryResult;
} catch (error) {
console.error("addUserDetails, an error occurred:", error);
} finally {
connection.release();
}
}
module.exports = {
create: addUserDetails
}
这也是我的泳池配置
PORT = 3000
DB_PORT = 3306
DB_HOST = localhost
DB_USER = root
DB_PASS =
【问题讨论】:
-
请同时提供
pool.getConnection()定义 -
await只有在等待承诺时才会做任何有用的事情。您的connection.query()没有返回承诺,因此await什么也不做。使用 mysql2 中的 promise 接口,以获得与 promises 一起使用的 mysql 数据库接口。 -
@jfriend00 我现在切换到 mysql2 但代码仍然不起作用
-
await pool.getConnection();内部发生了什么?也添加该代码 -
你读过mysql2中的promise接口吗?您必须使用该特定界面。只需在 NPM 页面上搜索“promise”,文档就在那里。我希望你能按照那里的指示。
标签: mysql node.js async-await