Vue method does not seamlessly handle async/await operations

Currently, I am engrossed in a Vue.js project where my main focus is on executing a series of promises that are interdependent. To simplify this example, I have omitted most of the code and replaced them with console.log statements to display the values I need to retrieve for later use. Once I can successfully make this example work, replicating it for the remaining tasks will be straightforward.

createBuilding: function() {
      return new Promise((resolve, reject) => {
        if(this.building === 'New building') {
          this.$store.dispatch('newBuilding', {
            address: this.address,
            number_units: this.number_units
          })
          .catch(err => {
            reject(err)
          })
          resolve(this.$store.getters.buildingID)
        } else {
          resolve(this.building)
        }
      }) 
    },
    onComplete: async function() {
      let buildingID = await this.createBuilding()
      console.log(buildingID)
      alert('Success');
    },

Actual Outcome:

Upon execution, the console.log first displays 'undefined,' followed by the alert pop-up, and then the awaited promise or function appears in the Vue DevTools.

I am seeking assistance on how to effectively obtain and utilize the result from the createBuilding method in conjunction with other methods within my project.

Answer №1

It's important to avoid the promise constructor antipattern. If a promise already exists and can be chained, there is no need to use new Promise. Using new Promise in this case creates room for mistakes, as seen here.

In this scenario, the issue arises because newBuilding is expected to be asynchronous but the promise is resolved instantly, causing a race condition.

The correct implementation should look like this:

createBuilding() {
    if(this.building === 'New building') {
      return this.$store.dispatch('newBuilding',...)
      .then(() => this.$store.getters.buildingID)
    } else {
      return Promise.resolve(this.building)
    }
},

If using async..await, the code simplifies to:

async createBuilding() {
    if(this.building === 'New building') {
      await this.$store.dispatch('newBuilding',...);
      return this.$store.getters.buildingID
    } else {
      return this.building
    }
},

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

Excluding a Spec File in Your Protractor Configurations

I have a scenario where I have 10 spec files all named *********.test.js. I need to run tests on all 9 of these files, excluding the file named Idontwantyou.test.js. Currently, I am locating my spec files in the config.file using: specs: ['*.test.js ...

Continuously performing a task in Node.js every 2 minutes until a JSON file, which is being monitored for changes every few seconds

In order to modify a process while my program is running, I need to manually change a value in a .json object from 0 to 1. Now, I want the program to: periodically check the .json file for changes. refresh a browser page (using puppeteer) every 2 minutes ...

Creating a custom if equals helper in Handlebars but encountering compilation errors

I have implemented a custom helper in Handlebars to create an if == "some string" type of helper. Here is the code for the helper: Handlebars.registerHelper('if_eq', function(a, b, opts) { if(a == b) // Or === depending on your needs ...

Creating an XML response to generate an HTML dropdown menu in PHP

My onChange function in javascript calls a PHP file to fetch UPS rates and update an HTML dropdown list. Everything was working fine until I needed to add an item to the options list based on a comparison. Javascript: function fetch_UPS(el){ var zip = ...

Adding a MTL texture to an OBJ in your three.js project is a simple process that can enhance

Hello! I am currently working on adding an MTL file to my OBJ in three.js. I had successfully loaded my OBJ and went back to address this issue. However, after adding the code to load the MTL file using MTLLoader, the code seems to be getting stuck at mt ...

Incorporating a variety of functions into an external javascript file

I am currently working on enhancing the functionality of a basic HTML page by incorporating JavaScript with multiple buttons. The problem arises when I attempt to introduce another function in my external JS file, as it causes the existing code to stop wor ...

Experiencing complications when retrieving API information in my React component

There is a json file available: {"area":[{"id":"1","name":"abc","address":"223 "},{"id":"2","name":"xyz","address":"123 "}] I am trying to fetch and display the data in my component using react and redux. Although I have successfully loaded the url with ...

Click event not triggering when rendering a JavaScript embedded Ruby partial

After re-rendering a partial with js.erb, why do click events stop working on the DOM? Following guidance from this tutorial, I successfully re-rendered a js.erb partial. However, when I attempt to trigger click events on buttons after clicking "cat.name" ...

Display content exclusively in PDF format

On my HTML page, I have two sections - one for inputting values and the other for viewing a PDF. To ensure that the PDF view is hidden until explicitly requested, I need it to remain invisible by default. It should only appear as a PDF when someone clicks ...

"Unexpectedly, JavaScript on Android ceases to function without any

Experiencing a frustrating issue with my application that involves a WebView and a html-page with JavaScript functions. Occasionally, the JavaScript functions fail to execute randomly. Despite spending the entire day trying to debug this issue, I can only ...

Using Vue to pass the v-for index from a parent component to a child component

Despite conducting thorough research, I am unable to find a satisfactory answer. Below is the code for my parent and child components. How can I pass the index from the v-for loop in the parent component to the child component so that it can be utilized th ...

The alignment of two elements is off in mobile display

Why aren't my two divs centered in mobile view? I am using Vuetify CSS flex helper justify-center to try and achieve it, but it doesn't seem to be working. Even when I use justify-sm-center, it still doesn't work. What am I missing? <v-co ...

The script is not functioning properly due to an error stating "(Uncaught ReferenceError: $ajaxUtils is not defined)"

I'm having trouble figuring out what the issue is (Uncaught ReferenceError: $ajaxUtils is not defined) document.addEventListener("DOMContentLoaded", function (event) { showLoading("#main-content"); $ajaxUtils.sendGetReque ...

Choose an image depending on the title, but only if a specific condition is met

var no_images2 = $j("img[title^='Click to enlarge image no_photo']").parent(); $j(no_images2).css('pointer-events','none'); var no_images3 = $j("img[title^='Click to enlarge image no_photo']").parent(); $j(no_images ...

how to use $emit to modify a computed property in VueJS

I have a form with multiple components for input fields, each containing another component for displaying errors. Here is the code: // Input component <template></template> <script> import Store from '../../store' exp ...

Execute a script to display an alert and redirect on Internet Explorer before an error occurs in Gatsby

I am currently operating a Gatsby site through Netlify, and I have encountered a specific error or crash that is only affecting Internet Explorer. In order to address this issue, I want to display an alert to users on IE and then redirect them to the Chrom ...

Set the text field to be editable or readonly based on certain conditions

Is there a way to conditionally enable or disable an editable field (edit/read only)? I have tried using session role from the database to set conditions on the text field, but I am unsure of how to proceed... <?php include('session.php'); ?& ...

How to use Typescript to find the length of an array consisting of either strings or

I am trying to determine the length of a string or array, stored in a variable with the data type var stepData : string | string[]. Sometimes I receive a single string value, and other times I may receive an array of strings. I need the length of the array ...

react validation for dropdown, react-datepicker, and hour input at intermittent intervals

I have integrated the following packages into my project :- react-datepicker library for selecting from time and to time date validation with date-fns, moment.js, additional validations using jQuery and lodash libraries/packages If you want to view my pr ...

I'm looking for ways to utilize the pageLoad function across multiple user controls

I am facing an issue with 3 usercontrols on a page. Each usercontrol has a pageLoad function in JavaScript, and the page itself also has a pageLoad function. However, only the pageLoad function of the last usercontrol that I registered is being fired, whil ...