繁体   English   中英

调用异步请求时如何避免重复?

[英]How to avoid repetition when calling async request?

我正在使用 Vue 2.6.10 和 Vuesax 3 来构建应用程序。

这个应用程序会像这样进行很多异步操作:

 async listResource() {
  this.$vs.loading(); //Start of the loading
  try {
    const response = await repository.get();
    this.list = response.data;
    this.$vs.notify({ title: "Success", text: "List fetched." });
    this.sdoSmething();
  } catch (err) {
    this.$vs.notify({
      title: err, //I´m not showing this error to the user, this is just to exemplify
      text: "There was an error when fetching the resource"
    });
  }
  finally{
    this.$vs.loading.close(); //Close the loading
  }
}

这种方法的问题是我一遍又一遍地重复很多代码。

如果我需要提出另一个请求,我将不得不创建另一个方法,如果承诺解决或失败,则发送特定消息......

抽象它的好方法是什么?

提供您的listResource方法参数以更改消息。 例如,两个将返回消息的回调函数 static 或基于这些回调的输入。

在下面的示例中,我编写了两个函数来构建消息 object。 successMessage为 static, errorMessage接收来自catch语句的错误。

两者都按参数的顺序传递给listResource方法,并在请求成功或失败时调用。

class YourClass {

  async listResource(success, error) {
    this.$vs.loading(); //Start of the loading
    try {
      const response = await repository.get();
      this.list = response.data;
      this.$vs.notify(success());
      this.sdoSmething();
    } catch (err) {
      this.$vs.notify(error(err)); // Pass the message.
    } finally {
      this.$vs.loading.close(); //Close the loading
    }
  };

}

const successMessage = () => ({ 
  title: "Success", 
  text: "List fetched." 
});

const errorMessage = err => ({
  title: err,
  text: "There was an error when fetching the resource"
});

const instance = new YourClass();
instance.listResource(successMessage, errorMessage);

// Or inside the instance.
await this.listResource(successMessage, errorMessage);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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