I have api's that queries the data and returns the results in json format. if i call the query inside api.get and set the res.send(rows) it is working fine but i need to call that same method in different methods so I thought I could write it outside and call that method whenever it is needed. but the result returns empty when it is outside.
var customerRows[]
app.get('/customers', function(req, res) {
getCustomers();
res.json({
customers : customerRows
});
});
function getCustomersQuery(callback) {
var customersDataQuery = mysqlConnection.query('SELECT * from customer_info', function(err, rows, fields) {
if (!err) {
if (rows) {
callback(null, rows);
}
} else {
callback(err, null);
console.log('Error while performing Query.');
}
});
}
function getCustomers() {
getCustomersQuery(function(err, result) {
if (err) {
console.log(err);
} else {
customerRows.push(result);
console.log(customerRows)//prints values
}
});
console.log("Result : "+customerRows);//prints empty
}
I'm trying to set the result to my global variable customerRows but it returns empty.
use this code
app.get('/customers', function(req, res) {
getCustomersQuery(function(err, result) {
if (err) {
console.log(err);
}
res.json({
customers : result
});
});
});
function getCustomersQuery(callback) {
var customersDataQuery = mysqlConnection.query('SELECT * from customer_info', function(err, rows, fields) {
if (!err) {
if (rows) {
callback(null, rows);
}
} else {
callback(err, null);
console.log('Error while performing Query.');
}
});
}
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.