Ways to resolve the issue of "await not waiting"

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.

Answer №1

The function getLastDayVisitors does not return anything nor does it wait for anything, causing the promise to immediately resolve as undefined without waiting for any asynchronous tasks to complete.

To address this issue, modify getLastDayVisitors to utilize the await keyword since it is already marked as async.

Additionally, refactor sumMonth to use only await instead of mixing with .then, choose one approach for consistency.

async function getLastDayVisitors() {
    const result1 = await Counter.find({date: {$gte: beforeYesterday, $lt:yesterday }});
    //get the totalVisitors of yesterday
    const TotalVisitorYesterday = result1[0].totalVisitors;
    //query - general
    const result2 = await Counter.find({name: 'general' })
    //get the totalVisitors overall
    const TotalVisitorOverAll = result2[0].totalVisitors;
    //return the delta
    return (TotalVisitorOverAll - TotalVisitorYesterday);
}

Rewrite sumMonth since it is also declared as async.

async function sumMonth() {
    const today = new Date();
    if (today.getDate() == 1) return 0;
    const todayTotalVisitor = await getLastDayVisitors();
    //query - last yesterday
    const result1 = await Counter.find({date: {$gte: beforeYesterday, $lt:yesterday }})
    //get the totalVisitors of yesterday
    const monthlyYesterday = result1[0].monthly;
    //calculate total visitors for today
    return todayTotalVisitor + monthlyYesterday;
}

Note that error handling has been omitted in this snippet, considering its placement may introduce more issues than solutions.

Execute sumMonth using either .then method or within an async function.

sumMonth()
.then(result => doSomethingWith(result))
.catch(err => handleTheError(err));

Alternatively, implement sumMonth in an async function for streamlined error handling.

try {
    result = await sumMonth();
    // perform desired actions with the result
} catch(err) {
    // handle errors here
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to conceal or deactivate button controls on videojs?

I am building an application using video.js and Vue. I am looking for a way to hide or disable certain controls like the play button, playback rate, and make the progress bar read-only. In the video.js documentation, I found that using controls: false hi ...

Attempting to launch my node.js application by integrating it with Mlab's MongoDB service

After following a tutorial on YouTube, I successfully created a project using Node.js, Express in VS Code, and a local MongoDB. However, I decided to take it a step further by utilizing Mlab (Cloud MongoDB) instead of my local database. I managed to migrat ...

Unable to invoke a mixin function within a JavaScript function

I've been experimenting with a small project utilizing nuxt.js, and currently, I've developed a plugin using mixins as shown below. However, I'm puzzled as to why function b is not working inside the render function: import Vue from 'v ...

Display advertisement in full screen on mobile devices with no need for scrolling bars

I am looking to develop a webpage using HTML/CSS/Javascript that can display an advertisement in full screen on mobile devices like smartphones and tablets. The ad should expand to the maximum width and height of the screen without any scrollbars. I have ...

Tips for splitting a container of specific height into sections measuring 80% and 20%

I am working on a container with a fixed position that I want to split into two halves: 80% and 20% at the bottom. This is what I want it to look like: Click here to see the image. Note: The layout should adjust itself when the window is resized. You c ...

Why isn't the click event triggering MVC 5 client-side validation for ajax posts?

To incorporate client-side validation with a click event for ajax posts, I followed a guide found at the following URL: Call MVC 3 Client Side Validation Manually for ajax posts My attempt to implement this involved using the code snippet below: $(&apos ...

There seems to be an issue with the VueJs + ElementUi Change method as it is

Just starting out with Vue and Element UI. I'm attempting to create a custom component using the ElementUI autocomplete/select feature. The problem I am facing is that the @change method does not contain a event.target.value value. When I try to acc ...

Enhancing User Interfaces with JQuery UI Widgets and Dynamic AJAX Calls

Currently involved in geolocation and mapping work, I am creating a JQuery widget to ensure that the code is portable for future projects. However, I have hit a roadblock when it comes to making an AJAX request. Below are a couple of methods from my widge ...

extract data from text using regular expressions to retrieve two values

Can someone assist with creating a regex expression to parse this string in JavaScript: $D('make').onChange('s',123456789,'a',10) I am trying to extract the values 123456789 and a from this string. Any help would be appreci ...

Converting javascript html object lowercase

Is there a way to dynamically adjust the height of specific letters in my label? Right now, I am overriding the text for the elements: let element = document.getElementById('xxx') element.textContent = 'Label' I attempted using <sup ...

Hide the div element when the url contains the word 'word'

I did some research online, but I couldn't find any information on whether this is doable. I'm currently using IPBoard and after their latest IPS4 update, I'm facing an issue where I can't simply change the homepage anymore. Now, I have ...

Repair the masthead background during overscroll

The Dilemma At the top of my webpage, I have a sleek masthead with a captivating background image that scrolls along with the page. However, there is an issue when users overscroll upwards, causing an undesirable white overflow to appear. To rectify this ...

Utilizing directives while initiating dynamic components

I've been exploring the capabilities of dynamically creating components using the ComponentFactoryResolver. const factory = this.componentFactoryResolver.resolveComponentFactory(FooComponent); const component = this.templateRoot. ...

Uploading images using the power of Angular and Node.js

I have been struggling with a persistent issue for quite some time now, and I have not been able to find a solution anywhere. My goal is to allow users to update their avatars on their profiles. However, every time I attempt to pass the file to my node ser ...

In JavaScript, constructors do not have access to variables

Currently, I am attempting to implement Twilio Access Token on Firebase Functions using TypeScript. export const generateTwilioToken = functions.https.onRequest((req, res) => { const twilioAccessToken = twilio.jwt.AccessToken; const envConfig = fun ...

Issue with npm installation leading to missing node_modules directory

When attempting to run npm install . in a local directory, I keep encountering the following errors: npm ERR! install Couldn't read dependencies npm ERR! Darwin 15.2.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "." npm ERR! no ...

How can we use SWR to fetch user data conditionally based on their logged-in state?

I am facing an issue with setting the UI state based on whether a user is logged in or not. The UI should display different states accordingly. I am currently using SSG for page generation and SWR for user data retrieval. However, I noticed that when call ...

Critical bug discovered in fundamental Vue.js component by Internet Explorer

My Vue.js-powered application is performing flawlessly in all web browsers, except for one... Upon attempting to launch it on Internet Explorer, a frustrating error appears: An anticipated identifier in vue.min.js, line 6 character 4872 Locating the spe ...

Error message in ReactJS with Axios and NodeJS: Unable to read property 'ownerDocument' of null with _id

I'm facing an issue with my ReactJS app that is connected to a Node backend using Axios. When trying to update, the payload seems correct, but I encounter a peculiar problem - it claims that I am not sending the required _id for updating. Below are sn ...

The smooth transition of my collapsible item is compromised when closing, causing the bottom border to abruptly jump to the top

Recently, I implemented a collapsible feature using React and it's functioning well. However, one issue I encountered is that when the collapsible div closes, it doesn't smoothly collapse with the border bottom moving up as smoothly as it opens. ...