在继续之前等待带有 axios 的方法完成

Wait for a method with axios to complete before proceeding

我正在学习 vue.js 并坚持承诺的概念。我希望使用来自 API 调用的数据初始化我的变量之一,并且我想确保 axios 调用是通用的:

{
  data: {
    list: [],
  },
  methods: {
    ShowList: function () {
      return this.Axios_GET('/api/Api_Store').then(items => {
        this.list = items;
      });
    },

    Axios_GET: function (apiurl) {
      // I want to keep this as a reusable method and don't want  to bind variable inside this method
      this.StartProgress();
      axios({ method: 'get', url: apiurl }).then((response) => {
        this.StopProgress();
        return Response.data;

      }).catch((error) => {
        this.StopProgress();
      }).then(function () {

      });
    },
  }
};

当我尝试 ShowList 时,出现以下错误:

Error in mounted hook: "TypeError: Cannot read property 'then' of undefined"

我想设置 ShowList 函数以从 API 获取数据,如下所示(概念上)

this.list = this.Axios_GET('/api/Api_Store') 

注意:StartProgressStopProgress 函数已经定义并且工作正常。

删除 axios 承诺链末尾的空 then() 并使用 Promise.reject() 在 catch 块中传播错误。最后,return 来自函数的轴承诺链。

如果您当时不传播错误,promise 将变为已解决状态并且您的 ShowList 函数将中断。

修改后的代码如下:

{
  data() {
    return {
      list: []
    };
  },
  methods: {
    ShowList: function () {
      return this.Axios_GET('/api/Api_Store').then(items => {
        this.list = items;
      })
      .catch((err) => {
        // Handle error here (Show warning/error)
        this.list = [];
      });
    },

    Axios_GET: function (apiurl) {
      
      this.StartProgress();
      
      // RETURN is important.
      return axios({ method: 'get', url: apiurl }).then((response) => {
        this.StopProgress();
        
        return response.data;
      }).catch((error) => {
        this.StopProgress();

        return Promise.reject(error);
      });
    },
  }
};
{
  data: {
    list: [],
  },
  methods: {
    ShowList: function () {
      return this.Axios_GET('/api/Api_Store').then(items => {
        this.list = items;
      });
    },

    Axios_GET: function (apiurl) {
      // I want to keep this as a reusable method and don't want  to bind variable inside this method
      this.StartProgress();
      axios({ method: 'get', url: apiurl }).then((response) => {
        this.StopProgress();
        return response.data; // <--- I think here needs to be response.data not Response.data, think this will help

      }).catch((error) => {
        this.StopProgress();
      }).then(function () {

      });
    },
  }
};

这是使用承诺链的方式。

{
  data: {
    list: [],
  },
  methods: {
    ShowList: function() {
      return this.Axios_GET('/api/Api_Store').then(items => {
        this.list = items || [];
      });
    },

    Axios_GET: function(apiurl) {
      this.StartProgress();
      return axios({
          method: 'get',
          url: apiurl
        })
        .then(response => response.data)
        .catch((error) => {
          // handle error if needed;
        }).finally(() => {
          this.StopProgress();
        });
    },
  }
};