I've been working on getting a function to output an array but nothing I do seems to let me return an array or access the array outside of the function.
I'm using node.js and mysql and am trying to pull row data, modify it, and then put it into an array. I seem to be able to put it into an array because within the function, I can console.log the variable I set the array to and I get what I'm looking for. But I can't get it out of the array. At first I was using forEach()
but have switched to using map()
.
Currently this is where I'm at:
let sql = "SELECT invoice FROM subscriptions";
myFunction = () => {
con.query(sql, (err, rows) => {
if (err) throw err;
var newArray = rows.map((row) => {
return row.invoice;
})
console.log(newArray)
})
}
myFunction();
If I change console.log(newArray)
to return newArray
there doesn't seem to be any evidence that this gives me what I'm looking for.
I've also tried to define variable outside of the function and then set the newArray to the variable outside of the function:
let sql = "SELECT invoice FROM subscriptions";
myArray = []
myFunction = () => {
con.query(sql, (err, rows) => {
if (err) throw err;
var newArray = rows.map((row) => {
return row.invoice;
})
myArray = newArray
})
}
myFunction();
console.log(myArray)
This only results in []
In this code, rows
is returning the invoice numbers from the subscriptions table. The result is:
[ '23480-13',
'23354-14',
'23728-14',
'23614-16',
'16132-14',
... more results ]
So console.log within the function seems to be correct. But if I try to return newArray
, as far as I can tell, the function is not returning anything.
This certainly seems like a simple problem but I've been stuck for hours. How can I create a function that will return an array I can use in a new function?