Having trouble getting async and await to function properly

Why is my code not waiting for validation and running the else part immediately? Can you help me find the mistake?


  async validateBeforeSubmit(event) {
        await this.$validator.validateAll().then(result => {
            if (result) {
                 console.log(result); // logging -> true
                // proceed with submission
            }else{
                console.log(result);  // logging -> false
                event.preventDefault();
                var elmnt = document.getElementById("drop_zone");
                elmnt.scrollIntoView();
            }
        })
        .catch(error=>console.log(error));
    },

I am using veevalidator and have defined some custom rules that take a few seconds to resolve:


 created() {
        this.$validator.extend('unique', {
            //   getMessage: field => 'At least one ' + field + ' needs to be checked.',
            async validate(value, arg) {
                arg = arg[0];
                let sw = false;
                if (arg == 'n_code') {
                    let data = {
                        'n_code': value
                    }
                    await Axios.post(duplicate_ncode, data, {
                        headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content') }
                    })
                        .then((response) => {
                            if (response.data == true) {
                                sw = true;
                            }
                        })
                        .catch(error => console.log(error));
                    if (sw) {
                        return true;
                    } else {
                        return false;
                    }

                }
                if (arg == 'email') {
                    let data = {
                        'email': value
                    }
                    await Axios.post(duplicate_email, data, {
                        headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content') }
                    })
                        .then((response) => {
                            if (response.data == true) {
                                sw = true;
                            }
                        })
                        .catch(error => console.log(error));
                    if (sw) {
                        return true;
                    } else {
                        return false;
                    }

                }
                if (arg == 'mobile') {
                    let data = {
                        'mobile': value
                    }
                    await Axios.post(duplicate_mobile, data, {
                        headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content') }
                    })
                        .then((response) => {
                            if (response.data == true) {
                                sw = true;
                            }
                        })
                        .catch(error => console.log(error));
                    if (sw) {
                        return true;
                    } else {
                        return false;
                    }

                }
            }
        });
    }

When a user fills all fields, it will check 3 APIs which take some time to respond. I need to await the results but something is not working as expected.

Please assist

Answer №1

Here is a suggested approach:

async validateBeforeSubmit(event) {
  try {
    const validationResults = await this.$validator.validateAll();
    if (validationResults) {
      // Proceed with form submission
    } else {
      event.preventDefault();
      var element = document.getElementById('drop_zone');
      element.scrollIntoView();
    }
  }
  catch (error) {
    console.log(error);
  }
},

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

Can a websocket be used to communicate with a server that is not the same as the one hosting the html5 website?

My goal is to establish communication between a hardware device and an HTML5 website. It seems like the best way to do this would be through WebSockets or possibly WebRTC over a WiFi network. Is that correct? I haven't come across any solutions invol ...

Error encountered upon initializing Node-RED due to the presence of an unexpected token while incorporating the NPM module "file-exists" into the

Currently, I'm in the process of developing an application using Node-RED and I'm looking to incorporate some NPM modules into my project. One particular module from James Thom caught my attention, called node-red-contrib-npm, which automates the ...

Inserting a multidimensional array into a JSON structure

Currently, I am working on populating my mongodb database with data that needs to be in a specific format. var location1 = [2,3]; var location2 = []; location2.push(location1); location2.push(location1); var location3 = []; location3.push(location2); cons ...

Discover the inner workings of the code below: set a variable called "start" to the current time using the new Date().getTime() method. Create a loop that continuously checks if

I'm having trouble understanding how this code snippet works. Can someone please provide a demonstration? Thanks in advance.... It seems that the code is subtracting 'start' from the current date with new Date, resulting in 0 which is less t ...

Utilize JavaScript to extract content from a text file and showcase it in a Bootstrap modal pop-up through knockout binding

I'm currently working on a function that reads data from a .txt file (located in the website's root directory) and then displays it in a modal dialog box. I believe I've made progress as the file is recognized during debugging, but unfortuna ...

Using Rails 5 and Ajax: Comments will only be appended if a comment already exists

I have been working on a new feature that allows users to add comments to articles using Ajax. However, I have encountered an issue where the comment only gets rendered successfully through Ajax if there is already one existing comment. The database commit ...

Generating a dropdown menu in HTML using JSON entities

I am attempting to populate an HTML Select element with data retrieved from JSON. Below is a simplified version of the JSON object: {"Group1": "TestGroup1", "Group2" : "TestGroup2", "TotGroups" : "2"} To achieve this, I am using JQuery and AJAX for fetch ...

Creating multiple objects using a single object in JavaScript can be achieved by using the concept of object

When presented with the following data structure: { "time_1": 20, "time_2": 10, "time_3": 40, "time_4": 30 } and expecting a result in this format: [ { "key1": "time_1" ...

Using PHP to identify the origin of a JavaScript file on a webpage

I have been attempting to locate an embedded stream link from a certain webpage. After inspecting the source code of the page, I found the following snippet: <script type='text/javascript'> swidth='640', sheight='460';& ...

Error: ReactJs unable to find location

I'm attempting to update the status of the current page when it loads... const navigation = \[ { name: "Dashboard", href: "/dashboard", current: false }, { name: "Team", href: "/dashboard/team", current: fa ...

Enhance the table using Django URL tag along with JQuery

I am currently working on a table that is being populated with user details and I would like to include a Django URL tag within the row, extracting the primary key in the process. Here is an example of what I am trying to achieve: function putTableData(re ...

What could be the reason for Sequelize to completely replace the record when updating in a put request?

I've been attempting to implement an "edit" feature within my project, but I've hit a roadblock in the process. Here's a snippet of the put request code: export const updateEvent = (event, id) => (dispatch, getState) => { request ...

Discover the ins and outs of the "DOM" within a string, treating it as HTML in AngularJS

Looking to extract data from a legal HTML string based on tags and attributes, but want to avoid using jQuery in favor of Angular. Are there built-in functions in Angular for this task? ...

Setting innerHTML does not affect the content of an SVG element

I am currently working on an Angular 7 application and I need to dynamically update the text value based on a dropdown selection. For example, if the id of the text element is 10, then I want to change the text from 'hi' to 'hello'. T ...

Direct your attention to the final item in a visible array within a ReactJS component

Currently, I'm in the process of developing a chat application using reactjs and am faced with the challenge of adjusting focus to the latest message whenever a new one is added to the array. The structure of my react chat window is as follows: < ...

I am unable to display the service response in the Angular component

I'm facing an issue with displaying data in an angular component from a service. The process from the service to the component seems fine, but when I try to use the variable in HTML, it doesn't show the result. For this project, I am using the M ...

Is it possible to update the content page without having to refresh the master page?

Our website features a Master page with main menu options and corresponding sub menus. When a user clicks on a main menu item, the relevant sub menus should be displayed. After clicking on a sub menu, the content page should update without having to refr ...

Accessing array values depending on DOM response

Generate a string from selected DOM elements I have an object that contains months and their corresponding index numbers (not dates) monthList = {"jan" : "1", "feb" : "2". etc: etc} The user can input values like jan or jan,feb,march and I need to return ...

Replacing HTML text with JSON data can be easily achieved by using JavaScript

After receiving data from an API and converting it into JSON format, I encountered difficulty when attempting to change a selected element in HTML. Every time I tried to do so, I either got 'undefined' or 'Object Object' as the output. ...

Enhancing user input with multiple values in a textarea using JSTL

I'm having trouble inputting multiple values into a textarea using JSTL. Here is the coding snippet I am using: <label>Resources</label> : <c:forEach items="${MEETING_ENTITY}" var="resource"> <textarea id ...