提问者:小点点

如何让mysql nodejs在查询加载后发送变量


我查过许诺,但找不到,我也不明白。 我知道其他一切都工作,并发送数据到客户端,只是空。 这是因为我无法在sql完成时及时赋值变量吗?

app.post('/api', urlencodedParser,function(req, res,next) {

  console.log(req.body);
  var data = req.body.productObjs;
var bool;


  data.forEach(function(product) {

    connection.query(`SELECT * FROM productInfo where specId = ${product.productSpec}`,function(error,rows){
      
(error,rows)=>{

      if (error) {
        next('error making the query: ' + error.message)
      }
       else {
        console.log(rows[0]['specId'])
        console.log(rows[0]['productPrice'])
        if (product.productPrice === rows[0]['productPrice']) {
      bool=true
        }
        if (product.productPrice !== rows[0]['productPrice']) {
bool=false
        }
      }
    })

});
 //res.send({"bool":bool})
})
})

共1个答案

匿名用户

因此,第一个明确的问题是,在一个回调中有一个回调。 这将是我第一次尝试重构:

app.post('/api', urlencodedParser, function (req, res, next) {
  console.log(req.body);
  const data = req.body.productObjs;
  let bool;

  data.forEach((product) => {
    connection.query(`SELECT * FROM productInfo where specId = ${product.productSpec}`, (error, rows) => {
      if (error) {
        next('error making the query: ' + error.message);
      } else {
        console.log(rows[0]['specId']);
        console.log(rows[0]['productPrice']);
        bool = product.productPrice === rows[0]['productPrice'];
      }
    });
  });
});
  1. 我被删除了双回调
  2. 将值分配给boolvariable
  3. 的简化条件
  4. 更改了现代JS语法的类型

相关问题