变量未保留价值

时间:2019-08-30 06:02:53

标签: javascript mysql node.js

我正在尝试将一个变量设置为从查询获得的结果,但是该变量未保留该值。

var queryString = "SELECT price FROM menu_items WHERE id = " + 
    req.query.items + ";";
mysql.pool.query(queryString, function(err, rows, fields){
    if (err){
        next(err);
        return;
    }
    itemPrice = rows[0].price;
    console.log("item price is2: " + itemPrice);
});

console.log("item price is: " + itemPrice);

我希望它先打印"item price is2: 10.99",然后再打印"item price is 10.99",但是它打印的物品价格依次为undefineditem price is2: 10.99

3 个答案:

答案 0 :(得分:0)

var queryString = "SELECT price FROM menu_items WHERE id = " + 
    req.query.items + ";";
mysql.pool.query(queryString, function(err, rows, fields){
    if (err){
        next(err);
        return;
    }
    itemPrice = rows[0].price;
    console.log("item price is2: " + itemPrice);
    console.log("item price is: " + itemPrice);
});

任何网络调用都是异步运行的,因此一旦执行db调用,下一行便开始执行。

使用异步等待

const {promisify} = require('util');
(async ()=> {
    var queryString = "SELECT price FROM menu_items WHERE id = " + 
        req.query.items + ";";
        const query = promisify( mysql.pool.query).bind(mysql.pool);
        const result = await query(queryString)
            if (!result) {
                next(result);
                return;
            }
            console.log(result)
            itemPrice = result[0].price;
            console.log("item price is2: " + itemPrice);
            console.log("item price is: " + itemPrice);
})()

答案 1 :(得分:0)

var queryString = "SELECT price FROM menu_items WHERE id = " + 
    req.query.items + ";";
mysql.pool.query(queryString, function(err, rows, fields){
    if (err){
        next(err);
        return;
    }
    itemPrice = rows[0].price;
    console.log("item price is2: " + itemPrice);
    console.log("item price is: " + itemPrice);
});

答案 2 :(得分:0)

you can do it using following method

export const getPriceValue = async () => {

var queryString = "SELECT price FROM menu_items WHERE id = " + 
    req.query.items + ";";
mysql.pool.query(queryString, function(err, rows, fields){
    if (err){       
        return 0;
    }
    if(row) {
      return(rows[0].price);
    }

});
}
let priceValue = await getPriceValue();
console.log('price::', priceValue);