Execution order control of calling interface in created method

As we all know, Vue is a single-page application. When we load a page, some interfaces need to be called when the page is created, get data from the interface, and then render it on the page. To put it simply, the interface is called in the create phase of the hook function.

Writing like this is most likely very common

 But if we want to get the list data from the getList interface, and then use the obtained fields as parameters to call other interfaces, this method cannot get the value, because no matter the order you write in the hook function created How about, the default execution of network requests in js is asynchronous, they will send requests in order and then ignore them , it is uncertain who will return first.

I tried using $nextTick and put the function that needs to be called later in $nextTick, hoping that it can have a delayed effect. $nextTick is to execute a delayed callback after the next DOM update cycle ends, after modifying the data. Using $nextTick, you can get the updated DOM in the callback , and execute the delayed callback after the next DOM update cycle ends.

       this.$nextTick(() => {
         this.handleReceiveSamples()
       })

In short, the effect I expected did not materialize.

Then I thought about setTimeout. The timer is a direct way to solve the function execution sequence, but it also has disadvantages, because there is no way to determine the response time of the first calling interface. If the setting is too long, the user experience will not be very good. Setting If it is too short, if the server is changed or the network is too slow, subsequent interfaces will not be called, causing bigger problems. Before I wrote this article, I was criticized by a back-end colleague. Xiao X, you said you had changed it, but the interface was not adjusted at all. (Embarrassed! Cry)

So here’s the key point, we need to manipulate data when calling the interface, so calling other methods is naturally part of the data manipulation.

As long as the interface that needs to be deferred is written in the .then of the previous interface, it can be easily solved. (Why didn’t I think of that?)

export default {
  data(){
    return {
      data:{}
    }
  },
  created() {
    this.getList()  // 在这里调用第一个接口
  },
  methods: {
    getList(){
      getList().then(res=>{
        this.data=res.data  //  这里就可以从接口里拿到数据了
        // 这时候在调用第二个接口,就保证了在上一个接口后面执行
        this.handleReceiveSamples(res.data)  
      })
    }
  }  
}

Guess you like

Origin blog.csdn.net/m0_56683897/article/details/132289527