-1

i dont know why this returned undefined. I google and something but dont find the result...

function getItemPrice(item_id) {
    pool.query('SELECT item_price FROM bank WHERE item_id ='+item_id, function(err, row) {
        console.log(row[0].item_price);
        return row[0].item_price;
    });
}

This shows the price in the console, that works.

But here it shows than undefined

items.forEach(function(itemObj){
                var item_price = getItemPrice(itemObj.id);
                console.log(item_price);
            });

its a simple mysql query getting the price of an item

txen
  • 135
  • 1
  • 10

1 Answers1

0

pool.query is asynchronous function. getItemPrice return undefined, you need to return callback. Here is an example:

 function getItemPrice(item_id, cb) {
   pool.query('SELECT item_price FROM bank WHERE item_id ='+item_id, function(err, row) {
     return cb(row[0].item_price);
   });
 }

 getItemPrice(id, function(row) {
   console.log('Your row', row);
 });
Pablo
  • 586
  • 5
  • 14
  • Oh okay, i try it, but how to get that than out of the ` getItemPrice(id, function(row) {`? Cause i need that outside the `items.forEach` – txen Sep 03 '18 at 19:29
  • I think this is a bad practice. Knocking constantly in the database. Why can not you immediately return a set of identifiers? 'SELECT item_price FROM bank WHERE item_id in ('+collection.join(',')+') – Pablo Sep 03 '18 at 19:42
  • The result is:you do not request by the identifier, but send the whole array, so it will be faster and more practical – Pablo Sep 03 '18 at 19:46