I need to return a value from a function, which gets its information from a query. I'm having some trouble passing information from the query's anonymous function to the container function.
I tried creating an array in a higher scope (the container function) and having the query function write to the array per result, but that didn't seem to work. I also tried passing the array into the query's anonymous function. That did not appear to work either.
Here's my function (executed within Node):
function retrieveSales(connection,timeFrame) {
var sales = new Array();
connection.query('select * from sales_entries where date BETWEEN ? AND ?',
timeFrame,
function (err, rows, fields, sales) {
if (err) return callback(new Error('Failed to connect'), null);
connection.end();
for (x = 0; x < rows.length; x++) {
sales.push(rows[x]);
}
});
console.log('Sales Returned: ' + JSON.stringify(sales, null, 4));
return sales;
}
which result in 'cannot call method 'push' of undefined
.
How should I properly write to the sales
array so that I can return it with retrieveSales()
?