繁体   English   中英

节点MySQL异步执行查询

[英]Node MySQL Executing Queries Asyncronously

我有以下Node / Express路由,用于将数据发布到MySQL服务器。 它首先将一个新用户添加到表中,然后获取新用户的ID,并将更多信息添加到配置文件表中。 第二个查询依赖于第一个查询,因此它们按顺序运行。

我已经编写了以下代码,它可以正确运行并完成工作。

routes.post('/register', (req,res) => {
  console.log('api req: ', req.body)
  const email = req.body.email
  const password = 'test'// req.body.password
  if (!email || !password) return res.status(400).json({type: 'error', message: 'Please provide email and password'})
  const hash = bcrypt.hash(password, 10)
  // console.log('hash is ...', hash )
  var sqlquery = "INSERT INTO user (username, first_name, last_name, email, password) VALUES ('test@gmail.com', 'Dan', 'Brown', 'test@gmail.com', 'test')"

  db.query(sqlquery, (error, results) => {
    if (error) return res.status(400).json({type: 'error', message: error})
    if (results.length == 0) {
      // do something
    } else {
      // run another query based on results from previous query
      var profilequery = "INSERT INTO userprofile (user_id, address, age) VALUES (" + results.insertId + ", 'test address', 25)"
      db.query(profilequery, (error1, results1) => {
        if (error) return res.status(400).json({type: 'error1', message: error1})
        console.log("profile inserted, ID: " + results1)
      })
    }
    console.log("1 record inserted, ID: " + results.insertId);
    res.json({type: 'success', message: 'user registered', results})
    return results
  })
})

有两个问题:

问题1:此代码不是异步的。 我想在此代码上使用async / await。 非常感谢有人能帮助我将其转换为异步代码。

问题2:我尝试使用bcrypt哈希密码。 但是,如果我在查询中使用哈希值,则查询失败,因为bcrypt返回一个Promise,而不是实际的哈希密码。 我解决这个问题。

未经测试:

    asyncQuery = (query, args) => {
    return new Promise((resolve, reject) => {
        db.query(query, function (err, result, fields) {
            if (err)
                return reject(err);
            resolve(result);
        });
    });
}

routes.post('/register', (req, res) => {
    console.log('api req: ', req.body)
    const email = req.body.email
    const password = 'test'// req.body.password
    if (!email || !password) return res.status(400).json({ type: 'error', message: 'Please provide email and password' })
    const hash = bcrypt.hash(password, 10)
    // console.log('hash is ...', hash )

    const sqlquery = "INSERT INTO user (username, first_name, last_name, email, password) VALUES ('test@gmail.com', 'Dan', 'Brown', 'test@gmail.com', 'test')"

    let firstresult, secondresult;
    asyncQuery(sqlquery)
        .then(rows => {
            firstresult = rows;
            const profilequery = `INSERT INTO userprofile (user_id, address, age) VALUES ("${rows.insertId}", 'test address', 25)`;
            return asyncQuery(profilequery)
        })
        .then(rows => {
            secondresult = rows; 
        })
        .then( () => {
            console.log(`firstresult:${firstresult}`)
            console.log(`firstresult:${secondresult}`)

            res.json({ type: 'success', message: 'user registered', results })
        })
        .catch(rows => {
            console.log(`Error:${rows}`)
        })
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM