【问题标题】:Redux Form: returning a promise from asyncValidate using async functionsRedux Form:使用异步函数从 asyncValidate 返回一个承诺
【发布时间】:2018-09-08 20:05:51
【问题描述】:

我想使用 ES2017 async 和 await 语法从 Redux Form 中的验证函数返回一个承诺。我当前的功能如下所示:

export const asyncValidateUsername = values => {
  return async () => {
    if (!values.username) return;
    const data = await axios.get(`/validate/${values.username}`);
    if (data) {
      throw { username: `Username ${values.username} is already taken.`};
    } else {
      return { username: 'Valid username.' }
    }
  }
}

然后我用 lodash 的 debounce 函数包装这个函数:

const asyncValidate = _.debounce(asyncValidateUsername, 200);

我收到以下代码错误:

Uncaught Error: asyncValidate function passed to reduxForm must return a promise

我认为异步函数隐含地返回一个承诺。我的代码中是否有错误,或者这是 Redux Form 的错误?任何帮助将不胜感激。

【问题讨论】:

    标签: reactjs redux async-await


    【解决方案1】:

    Asycn 函数如您所说返回一个承诺,但您的顶级函数不是异步函数,它返回一个异步函数。我对 Redux Form 不太熟悉,但你可以这样尝试:

    export const asyncValidateUsername = async values => {
        if (!values.username) return;
        const data = await axios.get(`/validate/${values.username}`);
        if (data) {
          throw { username: `Username ${values.username} is already taken.`};
        } else {
          return { username: 'Valid username.' }
        }
    }
    

    【讨论】:

      【解决方案2】:

      似乎因为 _.debouce 正在包装它,它现在返回去抖动的值,这似乎不是一个承诺值。

      这个答案谈到 debounce 返回一个承诺......

      Debounce function implemented with promises

      【讨论】:

        【解决方案3】:

        您可以通过添加 asyncBlurFields: [] like 来防止此错误

        MyAwesomeForm = reduxForm({
          ...
          asyncBlurFields: [] 
        })(MyAwesomeForm)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-01-26
          • 1970-01-01
          • 2021-06-20
          • 2016-06-22
          • 1970-01-01
          • 1970-01-01
          • 2017-12-07
          相关资源
          最近更新 更多