简体   繁体   中英

Variable not retaining value

I am attempting to set a variable to results obtained from a query, but the variable is not retaining the value.

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

I expect it to print "item price is2: 10.99" and then "item price is 10.99" but it prints item price is undefined and then item price is2: 10.99

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

Any network calls, run asynchronously, so once the db call is made, the next lines start executing.

Using Async Await

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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