变量不保留值

我试图将一个变量设置为从查询获得的结果,但该变量没有保留该值。


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"但它打印项目价格是undefined然后item price is2: 10.99


四季花海
浏览 177回答 3
3回答

LEATH

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);})()

吃鸡游戏

you can do it using following methodexport 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);

BIG阳

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);});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java