Promise resolve 传递问题

问题背景:在使用vee-validate的时候,需要通过ajax实时检测用户输入值是否已存在,自定义了一个异步检测规则,并使用了事件节流

因为事件节流的原因,我将检测函数抽出来,并想通过将参数保存在this中进行传递,可是结果并不像我想的那样

async function check() {
  const res = await Vue.prototype.$api.checkIfParamsValueExist(this.key, this.value)
  let valid = res ? res.info : true
  this.resolve({
    valid,
    data: valid ? '' : { message: '已存在' }
  })
}

Validator.extend('notExist', {
  getMessage: (field, params, data) => {
    return (data && `${field} ${data.message}`) || 'Something went wrong';
  },
  validate: (value, [key]) => {
    return new Promise(resolve => {
      console.log(value)
      this.value = value
      this.key = key
      this.resolve = resolve
      console.log('resolve', resolve)
      throttle(check, this, 800)
    })
  }
});

在进行表单验证的时候v一直在pending中,无法执行到then里面,可是我在上面已经resolve了

const v = this.$validator.validateAll()
console.log(v)
v.then((result) => {
   console.log('validateAll result', result)
})

如果我直接将check函数定义在给节流函数传参的时候是会可以正常运转的,但这样节流函数就没作用了

Validator.extend('notExist', {
  getMessage: (field, params, data) => {
    return (data && `${field} ${data.message}`) || 'Something went wrong';
  },
  validate: (value, [key]) => {
    return new Promise(resolve => {
      throttle(async function() {
        const res = await Vue.prototype.$api.checkIfParamsValueExist(key, value)
        console.log(res)
        let valid = res ? res.info : true
        resolve({
          valid,
          data: valid ? '' : { message: '已存在' }
        })
      }, this, 800)
    })
  }
});

附事件节流函数

function throttle(method, context, time = 100) {
  if (method.tId) {
    return
  }
  method.tId = setTimeout(() => {
    method.call(context)
    clearTimeout(method.tId)
    method.tId = 0
  }, time)
}
阅读 2.7k
1 个回答

原因是节流函数没有每次都resolve,修改后没问题了

function throttle(method, context, time = 100) {
  if (method.tId) {
    return context.resolve({
      valid: true,
      data: ''
    })
  }
  method.tId = setTimeout(() => {
    method.call(context)
    clearTimeout(method.tId)
    method.tId = 0
  }, time)
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进