消除异步方法

时间:2019-06-20 13:10:55

标签: javascript promise vuejs2 lodash debounce

目标-

在输入中添加实时验证,其中仅将验证的XHR部分去抖动

问题-

debounce添加到valueExists()会中断await。如果没有debounce,则await正确。

应如何处理?

methods: {
  async validate () {
    let local_errors = [];

    if (!!this.value && !this.$data.alpha_dash.test(this.value)) {
      local_errors.push('Invalid character');
    }

    if (!!this.value && await this.valueExists()) {
      local_errors.push('Already used');
    }

    return local_errors;
  },

  valueExists: _.debounce(function () {
    return axios.get(route('organization.slug.exists', { slug: this.value }))
      .then(response => {
        return false;
      })
      .catch(error => {
        return true;
      });
  }, 1000)
}

1 个答案:

答案 0 :(得分:0)

向已反跳功能添加异步应该可以:

valueExists: _.debounce(async function () {
    await axios.get(route('organization.slug.exists', { slug: this.value }))
      .then(response => {
        return false;
      })
      .catch(error => {
        return true;
      });
  }, 1000)
相关问题