如何将反跳应用于以下(code from Yup's github)的异步验证?

let asyncJimmySchema = string().test(
  'is-jimmy',
  '${path} is not Jimmy',
  async (value) => (await fetch('/is-jimmy/' + value)).responseText === 'true',
});

最佳答案

您可以使用lodash.debounce自行实现:

import { debounce } from "lodash";

// ...

const ASYNC_VALIDATION_TIMEOUT_IN_MS = 1000;

const validationFunction = async (value, resolve) => {
  try {
    const response = await fetch('/is-jimmy/' + value);
    resolve(response.responseText === 'true');
  } catch (error) {
    resolve(false);
  }
};

const validationDebounced = debounce(validationNameFunction, ASYNC_VALIDATION_TIMEOUT_IN_MS);


然后在验证方案中:

let asyncJimmySchema = string().test(
  'is-jimmy',
  '${path} is not Jimmy',
  value => new Promise(resolve => validationDebounced(value, resolve)),
});

09-15 13:04