'How do I call a variable from a function in nodejs?
In the following code I want to call payment_amount outside of the function, I've tried declaring the variables with var to make them global variables, but I still can't seem to call them outside of the function.
var payment_amount;
con.query("SELECT payment_amount FROM transactions LIMIT 1",function(err,payment_amount,fields){
if(err)throw err;
payment_amount = JSON.stringify(payment_amount);
payment_amount = payment_amount.replace('[{"payment_amount":','');
payment_amount = payment_amount.replace('}]','');
payment_amount = parseFloat(payment_amount);
console.log(payment_amount);
return payment_amount;
});
console.log(payment_amount); //RESULTS IN 'UNDEFINED'
Solution 1:[1]
Your con.query() call is likely asynchronous. That means that you're getting to the console.log() before the function inside the .query() callback is completed. Here are some docs that generally outline how asynchronous code works in JS: Async docs
What ORM are you using to get to the database? You can usually find examples on how to use async/await for that ORM. The call might end up looking something more like...
const getPaymentAmount = async () => {
try {
const paymentAmountResult = await con.query("SELECT payment_amount FROM transactions LIMIT 1")
console.log(paymentAmountResult) // works!
///... your parsing code etc.
return thingYouWantToReturn
} catch (err) {
throw new Error(err);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Allxie |
