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

output an array based on a specified key/value relationship

Looking to filter results based on a key/value pair in an array? Consider this example array: .factory('dishesFactory', function (){ var factory = { dishes :[ {nameEnglish: 'TAPENADE', nameLocal: 'Tapenade', descript ...

What is the best way to dynamically insert a new row into a table, with each row containing a table heading and column?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="tbl" class="tbl1"> <tr> <th> mobileno </th> <td class='mo' id="mo_0"> </td> ...

Identifying iOS Opera Mini browsers using JavaScript

Is there a way to prevent a specific script from running on the IOS Opera Mini browser? The navigator.UserAgent method is not providing clear identification for this browser. The returned string looks something like this: Mozilla/5.0 (iPhone; CPU iPhone O ...

Using a CSS button to activate a JavaScript function: A step-by-step guide

My current project involves writing a script to change the color of text when a specific button is clicked. The idea is that clicking the "Change color1" button triggers the text color change using the following code snippet: <button onclick="myFunction ...

Struggling to retrieve scope data within directive from controller in AngularJS

As a newcomer to AngularJS, I have utilized a service to retrieve data from the backend and received it in the controller. Now, my task is to parse these values and dynamically generate elements in a directive. However, when attempting to do so, I am encou ...

Initiate a CSS animation only when a different animation has completed

I am trying to create a sequence of animations using 2 squares. I want the animation for the red square to start only after the blue square's animation is complete. How can I achieve this cycle of animations? .box { width: 100px; height: 1 ...

Anchor point located within a scrollable div with a fixed position

A unique challenge has presented itself with a div called #results that appears when words are entered into a text box, triggering relevant results. This particular div is fixed and scrollable, with pagination located at the bottom of the scroll. The iss ...

Image loading failure detected in ReactJS

In my current project using Reactjs (Nextjs framework), I encountered an issue where I am unable to display an image on a page without specifying the "height" and "width" attributes in the Image tag. I attempted the following code snippet but the image is ...

javascript making a button using an object

When trying to create a button from a JavaScript object, I am following this approach: for (buttonName in buttons){ var htmlbutton = '<button type="button" onclick="'+buttons[buttonName]()+'">'+buttonName+'< ...

Homepage divided in two sections akin to the Tumblr landing page

Have you ever visited www.tumblr.com and noticed the '30 reasons...' link on the registration page that slides up and reveals a second page? I've been trying to figure out how they achieve this cool effect. Most tutorials show how to scroll ...

"Exploring the incredible powers of Ionic2, Angular2, HTTP requests, and

Despite all the research I've done on observables, I still struggle to grasp how they function. The HTTP request code snippet is as follows: import { Component, OnInit, Injectable } from '@angular/core'; import { Http, Response, Headers, R ...

The hover effect is not activated by the mouse movement event

I previously encountered an issue related to flickering with an absolute div when moving my mouse, which I managed to resolve by increasing the distance between my mouse pointer and the div. Now, I am working on the next phase of my project: My goal is t ...

Steps for integrating external components into Laravel 5.3 with VueJs Routes

I am currently working with Laravel 5.3 and utilizing the built-in VueJs components. At this point, my goal is to implement routes into my project. I have attempted to use the following code, but unfortunately, it is not functioning as expected. const No ...

Jade console.log() not functioning properly as anticipated

Is it possible that I can just insert -console.log('hello') into any part of the jade code? It doesn't seem to be working, do you know what could be causing this issue? ...

Issues arise when attempting to launch a Vue project in a web browser

Typically, I have been using the following code to launch my Vue project in a browser: "scripts": { "serve": "vue-cli-service serve --open" } Recently, I started a new Vue2 project and upon running npm run serve, my b ...

Node.js/Express - unable to retrieve client body data on server

I am able to retrieve data from express but I am facing issues when trying to post data to express... client: <html> <button onclick="myFunction()">send</button> <script> const data = {"experience" : 0}; ...

Vue - Checkbox for selecting all items

As I am still learning Vue, please bear with me as I attempt to solve this issue. I currently have a v-for loop that generates a list of checkboxes. Each checkbox works independently when clicked. However, my goal, as the title suggests, is to have a sele ...

Ways to navigate through a webpage without encountering any overflow issues

My window is too small to scroll, but I still need the ability to do so. Is it possible to scroll even when the height of the container is not large enough to display the scrollbar? Below is the code I am using to achieve scrolling: setTimeout(function() ...

What is the best way to generate a new Object using an Object that contains Arrays?

I currently have a global array saved with a catalog and a list of items that the user has saved. My task is to generate a new array of Objects (with arrays) containing only the items saved by the user. I am working with javascript in react-native, and I ...

Determine whether an element has the capability to hold text content

Is there a surefire and reliable method to determine if an HTML element is capable of holding text, using only pure JavaScript or jQuery? For example, <br>, <hr>, or <tr> cannot contain text nodes, whereas <div>, <td>, or < ...