Using conditional statements with async await in Javascript can cause issues such as not functioning properly

After spending several hours on it, I find myself more and more perplexed about the inner workings of async/await. Currently, here's the code I'm dealing with:


    created: function () {

         Event.$on('open-stage', (stage) => {

            this.$validator.validateAll().then(() => {

                const validateFields = async () => {
                    const uniqueEmail = await this.checkIfUniqueEmail();
                    if(uniqueEmail) {
                       console.log('uniqueEmail is true'); // <-- this is what I need to achieve
                       Event.$emit('change-stage', this.wizardStage.successor);
                    }
                };

                validateFields();
            }).catch(() => {
                toastr.warning('Error');
                Event.$emit('change-stage-denied');
                return true;
            });
        });
    },

    methods: {
        checkIfUniqueEmail() {
            if (!this.player.email || !this.player.email.length) {
                return true;
            }

            this.$http.post('playerExists', {
                email: this.player.email
            }).then(response => {
                if (response.data.exists) {
                    toastr.error(Good');
                    Event.$emit('change-stage-denied');
                    return false;
                }
                return true;
            }).catch(error => {
                toastr.warning('Fail');
                Event.$emit('change-stage-denied');
                return false;
            });
        },
    }

The aim is straightforward - when the checkIfUniqueEmail() method returns true, I want to trigger a console.log and emit change-state. The issue I'm facing is that the constant uniqueEmail always ends up as undefined. How can I ensure that this only happens after the response from the checkIfUniqueEmail() function confirms it as true? What adjustments do I need to make? I am using vue.js 2.1.10.

Answer №1

Ensure that your method returns the promise

validateEmail() {
    if (!this.user.email || !this.user.email.length) {
        return true;
    }

    return this.$http.post('checkEmail', {
        email: this.user.email
    }).then(response => {
        if (response.data.available) {
            toastr.success('Email is available');
            EventBus.$emit('email-validated');
            return true;
        }
        return false;
    }).catch(error => {
        toastr.error('Email already exists');
        EventBus.$emit('email-validation-failed');
        return false;
    });
}

Answer №2

Take a moment to think about this:

    async function checkUniqueEmail() {
      var emailIsUnique = await validateUniqueEmail();
        if(emailIsUnique) {
          console.log('The email is unique'); 
        }  
    }
    
    function validateUniqueEmail(){
      return new Promise(resolve => {
      setTimeout(() => {
          resolve('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="701a1f181e0930120211061f5e131f1d">[email protected]</a>');
        }, 1000)
      })
    }
    
    checkUniqueEmail();

The scenario depicted above mirrors your current situation, highlighting that returning a resolved Promise can be an effective approach. Simply follow the example below:

this.$http.post('checkPlayer', {
    email: this.player.email
}).then(response => {
    if (response.data.playerExists) {
        toastr.error('Error');
        Event.$emit('status-change-denied');
        return new Promise(resolve => {
           resolve(true)
        };
    }
<...>

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

Implementing X.PagedList within a modal pop-up window

I have implemented a modal pop-up on a webpage: ... <div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="companySearchModal" aria-hidden="true" id="companySearchModal"> <div class="modal-dialog" role="document"> ...

Using Angular 4 to delete selected rows based on user input in typescript

I am facing a challenge with a table that contains rows and checkboxes. There is one main checkbox in the header along with multiple checkboxes for each row. I am now searching for a function that can delete rows from the table when a delete button is clic ...

What is the method for utilizing Jquery to target the width value of an inline property?

I am struggling with selecting the "style=:width: 10%" value using jquery for a progress bar element in bootstrap. <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 10% ...

Determine the screen positions of the top edge of the bounding box in a three.js scene

On my three.js page, I have a set of particles rendering (you can find the demo and code here: ). This is how the default view looks like, with a unit cube centered at (0, 0, 0): To reveal the transparent bounding boxes surrounding each particle inside t ...

What specific types of errors is this try-catch block designed to catch and manage?

// This function establishes a connection to MongoDB using Mongoose const connectToDatabase = (url) => { return mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('Conn ...

Should the request be sent to the parent or child component?

When a page is divided into various components, the data for each component is fetched asynchronously. Therefore, the parent component should trigger the request and pass it on to the child component, or alternatively, the request can be directly sent to ...

Incorporate a directive dynamically within a separate directive

Introducing the table-div directive, which is responsible for rendering both the header and body of a table. Each row within tbody has the option to incorporate additional functionality through a custom directive that can display data linked to its parent ...

"Can you provide instructions on placing a span within an image

I am trying to figure out how to insert a <span> into an <image>, similar to the effect on the page . However, I do not want this effect to occur on hover(), but rather on click(). My goal is to insert "data-title" into the <span> and hav ...

Tips for simulating or monitoring a function call from a separate file

Within my codebase, there is a function that is triggered upon submission. After the payload has been posted, I aim to execute a function located in a distinct file named showResponseMessage: Contact.js import { onValueChangeHandler, showResponseMessage, ...

Make sure to correctly assign methods to their respective prototypes to avoid confusion

While working on my Electron app with jQuery, I keep encountering an error related to jQuery's tween function. I'm loading jQuery using standard node require: <script type="text/javascript>window.$ = window.jQuery = require('jquery&a ...

Why does the removeChild method in JavaScript consistently remove the last child element, rather than the one specified by its ID?

There are four divs with an event listener onclick, triggering a JavaScript function that simply removes the clicked div: this.parentNode.removeChild(this); Although it should remove the specific div clicked on, it instead deletes the last child and alte ...

Using recycled frame buffers in a threejs fragment shader

I'm currently working on a project to develop an app that emulates the effect of long exposure photography. The concept involves capturing the current frame from the webcam and overlaying it onto a canvas. As time progresses, the image will gradually ...

Adding a class to a clicked button in Vue.js

A unique function of the code below is showcasing various products by brand. When a user clicks on a brand's button, it will display the corresponding products. This feature works seamlessly; however, I have implemented a filter on the brands' lo ...

What is the most optimal location to retrieve data for authorized users in a Vue application?

Greetings! I am currently retrieving an array of posts from my express API in the Home.vue file, which is secured by route guards. <script> export default { created() { this.$store.dispatch('fetchPosts') } } </script> The fet ...

Using separate files for routes in Express.js can help organize and streamline your code

I'm facing an issue while setting up a node project where I need to organize my files. Specifically, I want to place a file routes.js within the routes/routes.js directory and controllers files in the controllers/ directory. For instance, let's ...

Invoking a parent method in ReactJS through two layers of components using TypeScript

I'm facing an issue while trying to call a method from a parent component that is two layers above. Whenever I attempt to do so, nothing happens or I get an error saying that the function is not defined. Here is my Child Component: class Child extends ...

Sending data between Angular and Python using both strings and JSON formats

Seeking assistance with a Python script that sends events to a server. Here is the code snippet: LOGGER = logging.getLogger("send_event") POST_EVENT_URL = "http://localhost:3000/event/" def send(name, data): url = POST_EVENT_URL + name headers = {& ...

Discover the most affordable price from an array in Vue Js

One of the challenges I'm facing involves working with an array that loops through all the trips for a listing. <span v-for="price in listing.trips"> <div class="price">{{ price.cost }} </div> </span> I'm wonderin ...

Parsing dates arriving from a Restful Service in JavaScript

When I make a Restful call, the JSON response contains dates in a strange format like this: /Date(-62135568000000)/ What is the simplest way to convert it to a normal date format like (January 10, 2016)? I have read some articles that suggest using rege ...

Using RxJS for various scenarios with Angular HttpInterceptor

Take a look at the following code block containing AuthInterceptor: @Injectable() export class AuthInterceptor implements HttpInterceptor { constructor(private authService: AuthService) { } intercept(req: HttpRequest<any>, next: HttpHand ...