提问者:小点点

在SQL查询中使用promise?


我有一个API调用,它需要从MySQL数据库中提取一些信息,以便完成请求。问题是,NodeJS不会等待查询响应,我已经尝试用承诺来解决这个问题。下面是我的代码:

app.post('/placeOrder', function (req, res) {
  var username = decryptAccessToken(req.body.AuthToken);
  console.log(username);
   con.query("INSERT INTO Orders SET ?", fetchCustomerInfo(username, req.body.orderInfo), function (err, response) {
     if (!err) {
      console.log("Order successfully placed");
      res.send("Order successfully placed");
     } else {
       console.log(err);
     }
   });
 });
 async function fetchCustomerInfo(username, orderInfo) {
  const query = new Promise((resolve, reject) => {
    con.query("SELECT FirstName, LastName, Address, Email, Phone FROM Customers WHERE Email=?", username, function (err, response) {
      var createOrder = {
        FirstName: response.FirstName,
        LastName: response.LastName,
        Address: response.Address,
        Email: response.Email,
        Phone: response.Phone,
        ProductInfoJSON: orderInfo
      }
      console.log(createOrder);
      resolve();
      return createOrder;
    })
  })
  await query;
  return query;
 }

这个FetchCustomerInfo函数将返回Promise对象,这将触发SQL语法错误,因为这不是预期的数据库输入。我做错了什么?任何建议都非常感谢。


共1个答案

匿名用户

试试看:



app.post('/placeOrder', async function (req, res) {
    var username = decryptAccessToken(req.body.AuthToken);
    console.log(username);
    var firstQuery = await fetchCustomerInfo(username, req.body.orderInfo);
    con.query("INSERT INTO Orders SET ?", firstQuery, function (err, response) {
        if (!err) {
            console.log("Order successfully placed");
            res.status(200).send("Order successfully placed");
        } else {
            console.log(err);
            res.status(500).send("Error!");
        }
    });
});
function fetchCustomerInfo(username, orderInfo) {
    return new Promise((resolve, reject) => {
        con.query("SELECT FirstName, LastName, Address, Email, Phone FROM Customers WHERE Email=?", username, function (err, response) {
            var createOrder = {
                FirstName: response.FirstName,
                LastName: response.LastName,
                Address: response.Address,
                Email: response.Email,
                Phone: response.Phone,
                ProductInfoJSON: orderInfo
            }
            console.log(createOrder);
            resolve(createOrder);
        })
    })
}