I am facing an issue where I need to set a variable x
to the result obtained from the showData
function. Below is my code snippet:
app.post("/view/show", (req,res) => {
let x = showData(req.body.custmerName);
console.log(x);
}
Here's how the showData
function looks like:
const showData = (custName) => {
const customer = mongoose.model(custName ,collectionSchema,custName);
customer.find( (error,data) => {
if (error){
console.log(error);
}else{
return data;
}
});
}
Despite successfully fetching data from the database and logging it using console.log(data)
, when I tried to log the value of x
, it displayed undefined
. This seems to happen because the console.log(x)
does not wait for the execution of showData()
due to JavaScript's synchronous nature. What can I do to ensure that the value returned by the function is properly logged instead of being shown as undefined
?