如何将去抖应用于下面的异步验证(代码来自 Yup 的 github https://github.com/jquense/yup#mixedtestname-string-message-string--function-test-function-schema) ?
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(validationFunction, ASYNC_VALIDATION_TIMEOUT_IN_MS);
然后在验证方案中:
let asyncJimmySchema = string().test(
'is-jimmy',
'${path} is not Jimmy',
value => new Promise(resolve => validationDebounced(value, resolve)),
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)