The async/await syntax can be finicky at times and may not always

Using Vue, I want to implement async/await to sequence my functions A and B.

Result is set to false by default.    

mounted() {
  this.A();
  this.B();
}

async A() {
  this.result = await this.$api...
}

async B() {
  if(this.result) {
    let data = await this.$another1 api...
  } else {
    let data = await this.$another2 api...
  }
}

I expect that after function A calls the API and returns a value for 'result,' function B will execute its job.

Sometimes, however, the API in function B calls 'another2 api' before 'this.result' gets its value even if the result is 'true' after function A receives a value from $api.

https://i.sstatic.net/3nIF3.png

This is the normal behavior I anticipate.

https://i.sstatic.net/6RLg3.png

This error occurs occasionally when I refresh the page.

How can I resolve this issue?

Answer №1

Ensure to define mounted as an async function.

async mounted() {
  await this.initializeA();
  await this.initializeB();
}

Answer №2

A function will return a promise. If your mounted() method is not async and cannot utilize await, you will need to use then.

this.A().then(()=>{
   this.B();
});

(Apologies, the code snippet above is in typescript. You'll have to adapt it to regular javascript as it's not my expertise.)

Answer №3

Make sure to instruct the mounted function to wait for the completion of the initial action before proceeding with the subsequent one. Don't forget to modify the mounted() function with the async keyword.

async mounted() {
  await this.performActionA();
  this.performActionB();
}

Answer №4

activated() {
  Promise.all([this.fetchData1(), this.fetchData2()])
         .then((response) => {
               console.log(response)
         })
}

async fetchData1() {
  const result1 = await this.$apiCall1...
  return result1
}

async fetchData2() {
  if(this.result1) {
         const data1 = await this.$fetchApi1...
         return data1
  } else {
          const data2 = await this.$fetchApi2...
          return data2
  }
}

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

RxJs will only consider the initial occurrence of a specific type of value and ignore any subsequent occurrences until a different type of value is encountered

I'm faced with a situation where I need to extract the first occurrence of a specific value type, followed by the next unique value of a different type. Let's break it down with an example: of(1,1,1,1,2,3,4) .pipe( // some operators ) .subsc ...

Tips for troubleshooting and debugging a Vue.js application using the Chrome browser

Recently, I decided to implement Vue.js as a templating tool for my Meteor app. However, when attempting to debug the code on Chrome browser, I encountered an issue where I couldn't locate the debugger pointer. It appears that debugging isn't fun ...

What are the best practices for implementing serialization in NestJS?

Recently, I delved into a fresh NestJs project and encountered a hurdle while trying to integrate serialization. The goal was to transform objects before sending them in a network response. Initially, everything seemed to be working smoothly until I attemp ...

Renaming personalized elements in Aurelia templates

My inquiry pertains to the process of aliasing custom elements and integrating them into aurelia's html-templates. To set the scene, I am utilizing the latest webpack typescript skeleton available at https://github.com/aurelia/skeleton-navigation and ...

What is the best way to utilize the filter search method within the SAILJS REST API?

Hey there, I'm having some trouble with generating a REST API in Sails.js. Here is the code for generating the API: sails generate api dentist This will create endpoints like /create, /update, /destroy, and /dentist. My question pertains to the /de ...

Return an array with only emails included

Looking to sort through an array specifically for emails, I attempted the following action emails = emails.filter((x)=>(x !== (undefined || null || ''))) To remove any empty values, while still allowing non-email values. ...

What steps should be taken to make mocha utilize the HTTP response?

Every time I make an http call, the function it returns causes my comparison to fail because [Function] is never equal to the value I want. Is there a way to make my assert statement consider the true/false flag within it? # test/helloWorld.js const othe ...

fullpage.js: the content exceeds the height limit

I am currently working on customizing the jquery script fullpage.js for a website built on the French CMS "SPIP" (). This script is used to create a one-page website with both horizontal and vertical navigation. However, I have encountered an issue with ...

Is the functioning of closures identical when applied to class methods?

Recently, I started learning React.js (along with Javascript) and I have a basic question to ask. I have created a small component that consists of 3 buttons. Each time these buttons are clicked, the value increments by one. Here is a working example: cl ...

How can I implement an AJAX request with MongoDB in Node/Express?

Let's begin with a simple webpage: an HTML Form, a button, and a div-box. When the button is clicked, the Form data will be sent via AJAX. The data will then be stored in MongoDB and retrieved into the div-box seamlessly without any page refresh. A ...

Update the JavaScript to modify the styling based on the specific value of the

Is there a way to apply specific style properties to images only if they already have another property? I've managed to achieve this with the following code snippet: if ($('#content p img').css('float') == 'right') $ ...

Identifying the moment when the body scroll reaches the top or bottom of an element

I have been experimenting with javascript and jquery to determine when the window scroll reaches the top of a specific element. Although I have been trying different methods, I have yet to see any successful outcomes: fiddle: https://jsfiddle.net/jzhang17 ...

Issues with displaying HTML5 audio player in iOS Chrome and Safari browsers

My html5/jquery/php audio player is working well on desktop browsers, but when I tried testing it on iOS, all I could see was a grey track bar. I suspect that the controls are hidden behind the track bar because sometimes the associated file starts playing ...

Please provide either a render prop, a render function as children, or a component prop to the Field(auto) component

While working on my project and implementing an Auto complete feature using final-form, I encountered the following error: Must specify either a render prop, a render function as children, or a component prop to Field(auto) In order to resolve this issue ...

Contrast and combine information from two JavaScript arrays of objects

I am struggling with comparing two arrays of objects based on a key. My goal is to compare the values, subtracting them when the keys match and displaying negative values for those not found in my target array. Additionally, I want to include all target o ...

Using JQuery to monitor the loading of a newly selected image src attribute

As a newcomer to JavaScript and JQuery, I am facing a challenge that I couldn't find a solution for in other discussions: I have a function that retrieves the path to an image (/API/currentImage) using a GET request and needs to update the src attrib ...

Tips for validating a URL in Cypress without having to actually visit the page

Is there a way to verify the URL without actually opening the page? The application is built on AngularJS and uses the ng-click method ($state.go) for navigation. I've researched Cypress stub and intercept options, but haven't found any solutions ...

Utilizing Material UI Pickers and Formik to efficiently handle Date, Time, and Second components

Currently, I am developing a React application with Formik that requires the utilization of date and time pickers. The app is being constructed using Material-UI and I have been exploring the possibilities provided by Material-UI Pickers at Given my relat ...

Guide on smoothly transitioning between 2 points within a requestAnimationframe iteration

Would it be possible to acquire a library for this task, or does anyone have any suggestions for my psuedocode API? Inquiry: How can I create a function that accepts 4 parameters interpolate(start, end, time, ease) and smoothly transition between the sta ...

`Optimizing bundle size in Webpack using braintree-web integration with TypeScript`

When utilizing braintree-web 3.61.0 with Vue.js 2.6.11 and TypeScript 3.8.3, I organize the necessary components of braintree-web into a service in this manner: import { client, hostedFields, applePay } from 'braintree-web'; export default { cli ...