首页 > 解决方案 > 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
        })
        })
    })
}

标签: javascriptmysqlnode.jsapiasynchronous

解决方案


这应该有效:

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
     }
}

推荐阅读