When I run an asynchronous function, I prefer to use the await declaration outside of the "then" method like this:
const todayTotalVisitor = await getLastDayVisitors();
This way, the await keyword does not wait.
async function calculateMonthTotal() {
const today = new Date();
if (today.getDate() == 1) return 0;
else {
const todayTotalVisitor = await getLastDayVisitors();
// querying for data from yesterday
Counter.find({date: {$gte: beforeYesterday, $lt:yesterday
}}).then((result1) => {
//getting total visitors from yesterday
const monthlyYestardy = result1[0].monthly;
//get today's total visitor count
return todayTotalVisitor + monthlyYestardy;
}).catch((err) => {
console.log(err);
});
}}
In this scenario, todayTotalVisitor may be undefined.
Definition of getLastDayVisitors function:
async function getLastDayVisitors() {
// querying data from yesterday
Counter.find({date: {$gte: beforeYesterday, $lt:yesterday
}}).then((result1) => {
// get the total visitors from yesterday
const TotalVisitorYesterday = result1[0].totalVisitors;
// querying general data
Counter.find({name: 'general' }).then((result2) => {
// getting total visitors overall
const TotalVisitorOverAll = result2[0].totalVisitors;
// calculating and returning the delta
return ( TotalVisitorOverAll-TotalVisitorYesterday);
}).catch((err) => {
console.log(err);
});
}).catch((err) =>{
console.log(err);
});
}
Thank you.