0

Hi guys im new to nodejs and web development in general, can anyone smarter then me please explain why my 'vResult = vResult.push(rows[e].label);' is not working as intented?

When i console the array after the block i get an empty array? Whilst rows[e].label has a value in the for loop itself.

Am i overlooking something?

const proc = require('../config/db_config');

function findMatch(vLabel){
    vToFind = vLabel;
    vResult = new Array();  

    proc.vPool.getConnection()
    .then(conn => {
        conn.query(`SELECT * FROM ${process.env.DB_N}.Panels WHERE label = '${vToFind}';`)
        .then(rows => {

            for (var e = 0; e < rows.length; e++){

                console.log(rows[e].url)
                vResult = vResult.push(rows[e].label);
            }
        })
        .catch(err => {console.log(err), conn.end})
    })
    .catch(err => {console.log(err), conn.end})

    return vResult;
}
module.exports = {findMatch};```
PrebenL
  • 13
  • 3
  • 1
    Check [the docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push), push appends to the array and returns the length of the array. – Phix Jun 28 '21 at 17:42
  • `array.push()` modifies the array in place, it doesn't return it. – Barmar Jun 28 '21 at 17:42
  • The docs should always be the first point of attack, especially when it's a JS built-in. Since your question regards `push` the docs would show you what `push` returns. The code still wouldn't *work*, because you'll need to wrap your head around async programming in general; see [How do I return the response from an aynchronous call](https://stackoverflow.com/q/14220321/438992). – Dave Newton Jun 28 '21 at 17:49
  • @DaveNewton, you are totally right my friend. I'm checking out that topic and starts to makes sense. Not really sure why i didnt look into that direction straight away. Was staring blindly thinking it was the the push. – PrebenL Jun 28 '21 at 17:55
  • @P_kidz It's both--you overwrite your array with the first push (and code should crash on the second) *and* return it too early :) When it rains, it pours. – Dave Newton Jun 28 '21 at 17:57

0 Answers0