Decorator @ is used in conjunction with async

purpose

prevents repeated submission of the form, so a loading value is set to control it. The code is modified as follows.

function setLoading(loading) {
  return function(target, name, descriptor) {
    const old = descriptor.value;
    descriptor.value = function() {
      // vue/react isLoading
      const isLoading = this.data[loading];
      if(isLoading) return;
      this.data[loading] = true;

      old.apply(this, arguments);

      // loading
      this.data[loading] = false;
      // datadom
      this.$update();
    };
    return descriptor;
  }
}

  @setLoading("isLoading")
  async getUserList() {
    // 
    const res = await backend.getUserList();
    if(res) {
      // 
    }
  }

there are two problems:

  1. I don"t know if what I wrote in this setLoading decorator is correct. I think everyone else is the last to get return old.apply (this, arguments);, but I have to execute the logic in the middle of the original function.
  2. because getUserList is an asynchronous function, this.$update () in the decorator executes backend.getUserList ahead of time. Eventually, the data request came back, but the dom could not be updated.

ask the boss for an answer. No, no, no. I was wondering if I could add a settimeout to the decorator. Force to delay this.$update (), but it feels too low

third question: I think based on the above setLoading code, the implementation will show the effect of loading only if the request time is greater than 300ms.

function setLoading(loading) {
  let timer = null;
  return function(target, name, descriptor) {
    const old = descriptor.value;
    descriptor.value = function() {
      // vue/react isLoading
      const isLoading = this.data[loading];
      if(isLoading) return;
      
      // 300ms
      timer = setTimeout(() => this.data[loading] = true, 300);
      
      old.apply(this, arguments);
      
      // loadingtimer
      clearTimeout(timer);
      this.data[loading] = false;
      // datadom
      this.$update();
    };
    return descriptor;
  }
}

then I gave it a try and manually adjusted the chrome network speed to slow 3G (slow, request time > 300ms). The results were as expected, and dom updated the data after the end of the loading. However, at the normal network speed (the request time < 300ms), loading will not appear, and the data will be requested, but the data of dom has not been updated.


< H2 > A brief introduction to the method decorator < / H2 > The decorator of the

method replaces the original method by modifying the original description object and returning a new description object.

  Decoration-Exploration of Arrowhead function  

					
Menu