This piece of code always returns undefined to the calling function. I'm new to JavaScript and I did try and look into some of the callback solutions on Stack Overflow and other resources but none of them worked for me. Any help with this would be highly appreciated. Thank you!
var funcs = require('./index.js');
var connected = require('./database')
query='SELECT * from trades'
const res = execute_rows(query)
console.log(res)
function execute_rows(query){
con = connected();
con.query(query, function(err, result, fields) {
if (err) {
return console.log(err);
}
console.log(result) //Displays correct results
return result; // Returns undefined to calling function
})
con.end();
}
CodePudding user response:
Harshith
Ok, if you print de result of your query inside the function execute_rows just before de return statement you should be able to see it.
The problem with your function is your not actually returning the result "on time". You need to return a promise to get the result from your function.
This could be a little hard to understand when you're new in JS. Your function should be something like this:
function execute_rows(query){
con = connected();
return new Promise((resolve, reject) => {
con.query(query, function(err, result, fields) {
if (err) {
// Returning the error
reject(err);
con.end();
}
resolve(result);
con.end();
});
});
}
Now, when you call you call your function, you have two options:
- Use async/await
- Still using promises (callback-driven)
Calling your function:
const dbResult = await execute_rows(query);
or
execute_rows(query).then(result => {
// Get the result
console.log('result:', result);
}).catch(error => {
// Get the error
console.log('error:', error);
});
Please, read about promises and async/await pattern!
Links:
Promises: https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Promise
Async/await: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await
