简体   繁体   中英

Weird order output. 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 don't have idea why my consol.log() performs in that order.

First i get answer from this

console.log("asdasd");

then

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

and last

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

I don't know why it ignore what is inside this.GetData() and performs this last.

Output

Since GetData makes an async request, you need to await it before proceeding so as to get a more predictable output.


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;
  }

axios.get(...) is an asynchronous function and returns a Promise . When the request is finished this promise will resolve and the .then(...) part is executed to process the result.

While the request is in progress (and thus we are waiting for a server response) the execution of the code continuous. It would be not really efficient if we are waiting for the (potentially slow) server response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM