Unexpected behavior with async/await in Vues.js

Despite appearing to run correctly, the console log indicates that the final result is being output before the inner await/sync.

    submitForm: function() {
      console.log("SUBMIT !");
      // vee-validate form validation request
      const makeValidationRequest = () => {
        return this.$validator.validateAll();
      };
      const validateAndSend = async () => {
        const isValid = await makeValidationRequest();
        console.log("form validated... isValid: ", isValid);
        if (isValid) {
          console.log("VALID FORM");
          // axios post request parameters
          const data = { ... }
          };
          const axiosConfig = {
            headers: { ... }
          };
          const contactAxiosUrl = "...";
          // send axios post request
          const makeAxiosPostRequest = async (url, data, config) => {
            try {
              const result = await axios.post(url, data, config);
              console.log("axios post request result: ", result);
              return true;
            } catch (err) {
              console.log("axios post request: ", err.message);
              return false;
            }
          };
          this.$store.dispatch("switchLoading", true);
          const sent = await makeAxiosPostRequest( contactAxiosUrl, contactAxiosData, axiosConfig );
          this.$store.dispatch("switchLoading", false);
          return sent;
        } else {
          console.log("INVALID FORM");
          return false;
        }
      };
      const result = validateAndSend();
      console.log("RESULT: ", result);
    },

the console log shows:

    SUBMIT !
    app.js:3312 RESULT:  Promise {<pending>}__proto__: Promisecatch: ƒ catch()constructor: ƒ Promise()finally: ƒ finally()then: ƒ then()arguments: (...)caller: (...)length: 2name: "then"__proto__: ƒ ()[[Scopes]]: Scopes[0]Symbol(Symbol.toStringTag): "Promise"__proto__: Object[[PromiseStatus]]: "resolved"[[PromiseValue]]: false
    app.js:3209 form validated... isValid:  false
    app.js:3291 INVALID FORM

I am expecting:

 SUBMIT !
 form validated... isValid:  false
 INVALID FORM

and also

 RESULT

Not sure what's causing the issue with my nested await/sync... thank you for any feedback

Answer №1

When calling the validateAndSend function, it immediately returns a promise.

Replace:

const result = validateAndSend(); 

with:

const result = await validateAndSend(); 

(and don't forget to add async to the submitForm)

This change allows us to wait for the promise to be fulfilled before logging the result.

Answer №2

Eliminate the makeValidationRequest function as it serves no purpose and is incorrect. Consider using this alternative approach:

submitForm: async function () {
  // check form validation status
  let formIsValid = await this.$validator.validateAll()

  let url = ''
  let formData = {}
  let config = {
    headers: {}
  }

  const postData = async (url, data, config) => {
    try {
      // display loader before sending request
      this.$store.dispatch('switchLoading', true)
      // send post request and retrieve response.data
      let {data} = await axios.post(url, data, config)
      // log success message if request is successful
      console.log(`form post successful: ${data}`)
    } catch (err) {
      // log error message if request fails
      console.log(`error posting data: ${err}`)
    } finally {
      // hide loader regardless of request outcome
      this.$store.dispatch('switchLoading', false)
    }
  }

  formIsValid && postData(url, formData, config)
  // do not proceed if form is invalid
}

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

Is there a way to retrieve the current logged in user when working with socket.io?

When it comes to retrieving the logged in user using passport.js in most of my routes, it's a breeze - just use req.user.username. However, I've encountered an issue with a page that relies solely on websockets. How can I determine the username o ...

Node - Creating personalized error handling functions

Currently in the process of developing custom helper methods to eliminate redundancies, utilizing express-promise-router app.js has set up the error handler middleware //errorHandler app.use((err, req, res, next) => { //const error = a ...

angularjs code to dynamically change the selected index of an option in a document

This code snippet demonstrates how to achieve this functionality using pure JavaScript: document.getElementById("mySelect").selectedIndex = "0" <select class="selectpicker" id="mySelect"> <option>English &nbsp;</option> < ...

Looking to construct a multidimensional array in JavaScript for efficiently reading arrays along with their corresponding options?

I am looking to create a multidimensional array in JavaScript to store questions along with their related options. Here is my current code snippet: demoArray[i] = new Array(); var id=results.rows.item(i).del_ques_id; demoArray[i]["question"] = results.row ...

Vuex getters consistently seem to yield null values

Whenever I utilize a Vuex getter in my Vue.js component, it keeps returning null for me. Below is the code snippet: MainLayout.vue <script> import NavBar from '@/components/NavBar.vue' import ToolBar from "@/components/ToolBar" ...

creating a JSON object

Exploring JSON for the first time and I have a couple of questions: Is it possible to create a JSON object using the 'data-id' attribute and have it contain a single array of numbers? Even though I have the code to do this, I am facing difficul ...

Execute Validation Function on Every TextField and Radio Button

I'm new to Javascript and struggling to make my function work for both radio buttons and text fields. Here is the HTML code for the form: <form action="sendmail.php" method="post" name="cascader" onsubmit="prepareEventHandlers()" id="cascader"&g ...

The MUI Select component requires two clicks to open its menu if another Select component's menu is already open

I have been developing an application with two dropdowns (Select components) positioned next to each other, denoted as A and B. When A is open and the user intends to click on B to open it, I observed that in the default behavior of material UI, the user ...

Creating a delayed queue using RxJS Observables can provide a powerful and

Imagine we have a line of true or false statements (we're not using a complicated data structure because we only want to store the order). Statements can be added to the line at any time and pace. An observer will remove items from this line and make ...

Tips for efficiently utilizing AJAX requests in conjunction with PHP without duplicating code

I have a small script that utilizes AJAX and PHP to showcase an image. As you can see, by calling the mom() function, it searches the PHP file index.php?i=mom and displays the desired image. However, I am looking for a way to streamline the JavaScript cod ...

Tips for displaying errors in React applications

Having trouble troubleshooting React (16.13.0) as I am not receiving any useful errors, just this message: Error: Minified React error #321; visit https://reactjs.org/docs/error-decoder.html?invariant=321 for more info or switch to the non-minified dev en ...

Retrieve the initial occurrence that meets the conditions across three columns in MySQL

I am currently utilizing a NodeJS REST API that connects to a MySQL database. Within this database, there is a specific table we will refer to as Table_01: | C_0| C_1| C_2| C_3| | 1 | A1 | B1 | 1 | | 2 | A1 | B2 | 0 | | 3 | B1 | A1 | 0 | | 4 | A2 | ...

Tips for verifying a text input as an email address using JQuery

Can someone help me with writing an if statement that checks if two fields are empty and confirms if one of them is a valid email address? Also, how can I validate if the email address entered is indeed valid? var fullname = $("#name").val(); var emai ...

Give a radio button some class

<input id="radio1" type="radio" name="rgroup" value="1" > <label for="radio1"><span><span></span></span>1</label> <input id="radio2" type="radio" name="rgroup" value="2" > <label for="radio2"><span ...

Dropbox menu within an extended webpage

I am looking to create a dropdown menu that behaves like the one on this website. The goal is for the dropdown to cover the entire webpage, hide the scroll bar, and "unmount" the other elements of the page, while still displaying them during the transition ...

Creating interactive carousel slides effortlessly with the power of Angular and the ngu-carousel module

I'm currently tackling the task of developing a carousel with the ngu-carousel Angular module, available at this link. However, I'm facing some challenges in configuring it to dynamically generate slides from an array of objects. From what I&apos ...

Learn how to leverage dynamic imports for a single use case in NextJS

I am currently in the process of developing an App using NextJS and I am looking for a way to display a loading icon while fetching data or loading certain pages. Right now, I have to manually insert the Loading component into each individual component. Fo ...

Using Node.js and JWT: A guide to securely storing and using access tokens in the Authorization header

Has anyone encountered this issue before? I've searched extensively online but haven't found much information on the topic. I'm relatively new to using node and JWTs, and my goal is to generate a JWT and store it in the Authorization header ...

Incorporate an object property value into an established Angular/Node app by using the syntax " :12 " instead of just " 12 "

My current project is an Angular/Node MEAN stack application, but my primary concern revolves around JavaScript. When I receive a response object, it includes an SQL identity id console.log(response.recordset[0]); The output is "":12 I want to assign t ...

What could be the reason my dropdown menu is not appearing on hover?

Currently, I am in the process of developing a menu using angularJS and google app script within a dialog box. I have been referring to this sample code for guidance. Instead of pasting all my code here, I can summarize what I have come up with: var a ...