Strange sequence of results coming from Vue.js

methods: {
    ShowWindow: function(QueryID) {
        this.$data.ID = QueryID;
        if(this.GetData())
        {
            console.log("asdasd")
        }
        document.querySelector("#EditWindow").style.visibility = "visible";
        console.log(this.$data.RowData.name + "asdd");
        this.$refs.Title.SetName(this.$data.RowData.name + " " + this.$data.ID);
    },
    GetData: function(){
        const URI = localStorage.getItem("URI") + *URL part 2* + this.$data.ID;
        axios.get(URI, this.$parent.$data.optionsAxios).then((result) =>{
            this.$data.RowData = result.data;
            //console.log(result.data);
            console.log(this.$data.RowData.name);
        }).catch(err =>{
            console.log(err);
        })
        return true;
    }
},
mounted(){
    this.$data.ID = this.$route.params.UserID;
    this.ShowWindow(this.$data.ID);
    this.$data.TableName = this.$parent.TableName;
}

I can't figure out why the sequence of console.log() outputs is as it is.

Initially, I receive output from this:

console.log("asdasd");

followed by

console.log(this.$data.RowData.name + "asdd");

and finally

console.log(this.$data.RowData.name);

I'm puzzled as to why it skips over what's inside this.GetData() and shows this last.

View Output

Answer №1

To ensure a more predictable output, it is important to use the await keyword when making an asynchronous request with the GetData function.


methods: {
    ShowWindow: async function(QueryID) {
      this.$data.ID = QueryID;
      try {
        const result = await this.GetData()

        this.$data.RowData = result.data;
        console.log(this.$data.RowData.name);

        if (result) {
          console.log("asdasd")
        }

        document.querySelector("#EditWindow").style.visibility = "visible";
        console.log(this.$data.RowData.name + "asdd");
        this.$refs.Title.SetName(this.$data.RowData.name + " " + this.$data.ID);

      } catch(e) {
        console.log('error');
      }
    },
    GetData: function() {
      const URI = localStorage.getItem("URI") + * URL part 2 * +this.$data.ID;
      return axios.get(URI, this.$parent.$data.optionsAxios);
    }
  },
  mounted() {
    this.$data.ID = this.$route.params.UserID;
    this.ShowWindow(this.$data.ID);
    this.$data.TableName = this.$parent.TableName;
  }

Answer №2

The function axios.get(…) is asynchronous, meaning it does not block the execution of code and returns a Promise object. Once the HTTP request is complete, the Promise will resolve, triggering the .then(…) method to handle the response data.

While the request is being processed (waiting for a server response), the rest of the code can continue executing. This prevents the program from being inefficiently paused while waiting for the potentially slow server response.

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

Include a fresh attribute in the Interface

How can I include a boolean property isPhotoSelected: boolean = false; in an API interface that I cannot modify? The current interface looks like this: export interface LibraryItem { id: string; photoURL: string; thumbnailURL: string; fi ...

Using Vue along with bootstrap-vue: Ensuring only one list element is expanded in a list (v-for) at any given time

In my Vue project with bootstrap-vue, I am utilizing the b-collapse feature within a v-for loop for lists. While it is functioning correctly, I am struggling to automatically close expanded list elements when a new one is clicked. Here is my question: Ho ...

Switch between display modes by clicking using collections

I am trying to figure out how to create a function that will only show content for the specific element in which my button is located. Currently, when I click the button it shows content for all elements with the 'one' class, but I want it to dis ...

Using jQuery, learn how to successfully call a selector from dynamic content

I am currently facing a challenge with a table that is generated server-side and then appended to the view page (client-side). Since the table is not directly included in the DOM, I am using the StickyTableHeaders jQuery plugin to create a sticky header fo ...

Assistance required in translating Firebase syntax from version 7.15.1 to version 9.6.1

I'm embarking on my Firebase journey and trying to follow a tutorial that seems to be a bit outdated. I could use some assistance in updating the code to match the newer version, as it appears the syntax has changed. The tutorial uses Firebase 7.15.1, ...

Discovering the value of a checkbox using jQuery and Ajax

I have a challenge with sending the state of multiple checkboxes on my page back to the database using ajax. While I am comfortable working with jquery and ajax for SELECT and OPTIONS elements, I am struggling to do the same for checkboxes and extracting t ...

Combine the values in the array with the input

I received some data from the back-end which is being written to a form, and it's in the form of an array of objects Below is the code snippet: this.companyDetailsForm = new FormGroup({ directors : new FormControl(response?.companyDirectors) ...

What happens when there is no match found while attempting to edit a form with the UI-Bootstrap typeahead directive?

Here is the code that demonstrates how my typeahead input box functions. Users can enter a name, and the relevant information will populate the rest of the form. If no match is found, users should still be able to input the name and related details into th ...

Adjust the position of a textarea on an image using a slider

Currently, I am exploring how to creatively position a textarea on an image. The idea is to overlay the text on the image within the textarea and then use a slider to adjust the vertical position of the text as a percentage of the image height. For instanc ...

Implementing Do Not Track in an express application

I am trying to implement a feature named "consent" in my Nodejs express app that utilizes the Do Not Track (DNT) functionality from browsers. This function is supposed to integrate Google analytics on rendered pages only when DNT is not active or its state ...

Issue with utilizing the 'multiple' prop in Vuetify for uploading files

I've been working with Vuetify to create a form that features the option for users to upload multiple files. I have successfully included the 'multiple' prop to allow this functionality, but I am encountering an issue where uploading another ...

What is the best way to create a basic accordion using only certain table rows?

I am faced with the task of transforming a HTML table that lists various items. Each <tr> within the table contains a unique title element, but there are cases where rows can share the same title indicating their relation. My goal is to implement jQu ...

Node.js program experiences issues with incorporating netCDF files

I am attempting to encode a NetCDF file within my Node.js program using the netcdf library, which can be found at https://www.npmjs.com/package/netcdf. After running the program, I encountered the following error: C:\app [master +2 ~1 -0 !]> npm ...

The scrolling feature induces a contraction to the left side

Recently, I implemented the code below to fix my menu when scrolling the page: var num = 5; $(window).bind('scroll', function () { if ($(window).scrollTop() > num) { $('.scroll').css({'position':'fixed&apo ...

Guide to dynamically updating a textarea in vue.js by incorporating data from several inputs

Is there a way to update a textarea based on multiple inputs using jQuery and vue.js? I have successfully implemented the jQuery part with line breaks, but when I try to display the value of the textarea elsewhere using vue.js, it doesn't seem to work ...

Using Vue.js to add animation effects to elements

What is the best way to use the .animate function on an element in vuejs? <aside v-transition v-if="toggleMenu"> <a href="#">Haha</a> <a href="#">Nice</a> <a href="#">Menu</a> </aside> A similar piece ...

Encountering Next.JS Router Issue: Unable to Access Properties of Null (specifically 'useContext')

As a beginner in Next.js and React, I'm facing an issue with redirecting users from the "Projects" page to the Product Page Details. Here's the code snippet I am using: const openProjectDetails = () => { Router.push('/api/' + props ...

Vue: Error - Unable to execute _vm.myFunction as it is not a function

I'm currently working on adding a basic button to a .vue file that will log a message to the console. Here's the code I have so far: <template> <div> <button v-on:click="sayHello()">Click me</button> < ...

Prevent the onclick function of a span element from being triggered when the user clicks on a dropdown menu contained within

Just delving into the world of web development and currently tackling a React project. Encountered an issue where I need to make a span element clickable. However, there's a dropdown within that span that doesn't have any onClick event attached t ...

What is the best way to generate a fresh set of data from a search parameter?

I have received data from an API call that needs to be filtered. I am utilizing Redux instead of local state for this task. Below are the actions I have defined: import ActionTypes from '../constants/ActionTypes'; export const passengersDataAc ...