[Vuejs]-How to avoid repetition when calling async request?

0👍

Give your listResource method parameters to change the messages. For example two callback functions that will return a message, static or based on the input of those callbacks.

In the example below I’ve written two functions which will build a message object. The successMessage is static and the errorMessage takes in the error from the catch statement.

Both are passed to the listResource method in the order of the parameters and called whenever the request succeeded or failed.

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

Leave a comment