运行 多个方法使用 Async 和 Await 解析后的代码

Run code after multiple methods resolve with Async and Await

我有三种方法:

isSixCharactersLong(event) {
    const input_len = event.target.value.length;

    if (input_len === 6) {
        this.setState({isSixCharactersLong: true})
    } else {
        this.setState({isSixCharactersLong: false})
    }
}

isAlphanumeric(event) {
    const input_str = event.target.value;

    for (let i = 0; i < input_str.length; i++) {
        const code = input_str.charCodeAt(i);
        if (!(code > 47 && code < 58) && // numeric (0-9)
            !(code > 64 && code < 91) && // upper alpha (A-Z)
            !(code > 96 && code < 123)) { // lower alpha (a-z)
            this.setState({isAlphanumeric: true});
        } else {
            this.setState({isAlphanumeric: false});
        }
    }
}

isEmpty(event) {
    event.target.value ? this.setState({inputIsBlank: false}) : this.setState({inputIsBlank: true});
}

我想做的是运行这三个方法解决后的一个函数。所以我写了以下内容:

async handleValidation(e) {
    this.isAlphanumeric(e);
    this.isEmpty(e);
    this.isSixCharactersLong(e);
}

然后我有了这个由我的 React 应用程序触发的最终方法。

handleOnChange = async (e) => {
    await this.handleValidation(e)
        .then(() => this.setState({code: e.target.value}))
};

我认为这会起作用,但我一直收到 e 为 null 的错误。不知何故,我失去了 事件

我认为问题在于我没有在正确的方法上使用 async 和 await。

您可以将此代码缩减为,

handleOnChange = (e) => {
  const { value } = e.target
  const isAlphanumeric = /^[a-z0-9]+$/i.test(value)
  const isSixCharactersLong = value && value.length === 6
  const inputIsBlank = !!value // or Boolean(value)

  this.setState({ isAlphanumeric, isSixCharactersLong, inputIsBlank })

  if (!inputIsBlank && isAlphanumeric && isSixCharactersLong)
    this.setState({ code: value })
}

/^[a-z0-9]+$/i:不区分大小写测试字母数字的正则表达式

!!:类型强制转换为布尔值,即如果值为空,则为假,双重否定将其变为真并返回 false

编辑

根据评论中的讨论,为了仅在输入有效时设置 code,我添加了一个 if 语句,该语句本质上转化为,如果值不为空(!inputIsBlank) 如果值是字母数字并且输入是六个字符长则将 code 设置为 value.

当没有任何承诺时,您在两个函数中都使用了 async await,这都是同步代码,因此您实际上不需要 async await 来解决这个问题。也许写你的验证代码来抛出一个错误,如果没有通过,然后在 handleOnChange 里面你可以 运行 一个三元

 handleOnChange = (e) => {
    !this.handleValidation(e)? return :
         this.setState({code: e.target.value}))
};