javascript - MySQL NodeJS:MySQL 查询一起执行
问题描述
在下面的Controller.js
文件中,我想让第二个 mysql 查询等待第一个查询完成,然后使用第foundUser
一个查询中存储的数据。
我很难申请async await
,因为第二个查询正在接收一个空对象,因为它与第一个查询一起执行。
服务.js
addUser: (data) =>{
return new Promise((resolve, reject) => {
mysqlpool.query(`insert into requests_team(from_id, to_id)
value(?,?)`,
[
data.from_id,
data.to_id
],
(error, results, fields)=>{
if(error){
return reject(error);
}
return resolve(results);
}
);
})
},
控制器.js
addUser: async(req, res) =>{
const body = req.body;
let errors = {};
let foundUser = {}
const queryOne = await mysqlpool.query('SELECT id, email FROM registration WHERE email = ?', [body.email], (error, result)=>{
if(error){
console.log(error)
}
if(result.length > 0){
foundUser = result
}
});
const queryTwo = await mysqlpool.query(`This is where I want to use the value stored in foundUser ${foundUser[0].id}`, (error, result) => {
if(error){
console.log(error);
}
addUser(body, (err, results) =>{
if(err){
console.log(err);
return res.status(500).json({
success: 0,
message: 'Error'
})
}
return res.status(200).json({
success: 1
})
})
})
}
解决方案
这应该有效:
addUser: async (req, res) => {
const body = req.body;
let errors = {};
let foundUser = {}
const queryOne = await mysqlpool.query('SELECT id, email FROM registration WHERE email = ?', [body.email]);
if (error) {
console.log(error)
}
if (result.length > 0) {
foundUser = result
const queryTwo = await mysqlpool.query(`This is where I want to use the
value stored in foundUser ${foundUser[0].id}`)
// Do stuff with the queryTWo response here
}
}
推荐阅读
- javascript - Uncaught (in promise) TypeError: Cannot set property of undefined at eval in vue.js?
- python - 如何为列中的每个类别创建行?
- apache-kafka - 对于 Kafka,需要在 listeners 和 Advertisementd.listeners 值中设置哪些 IP 值?
- python-3.x - 格式化 json 数据以转换为 xslx
- data-structures - 我如何确定给定的代码是否可解码?
- c - 由于互斥锁而发生死锁时如何造成内核恐慌?
- command-line - 使用构建命令行构建规则项目 (ODM)
- android - 如何修复“时钟 getDataFormat getSystemString 失败”
- css - 如何实现精准的 CSS 渲染?
- laravel-5 - 碳更改语言为捷克语