是的-setTimeout

时间:2019-10-29 20:04:38

标签: javascript reactjs formik yup

为了保存请购单,下面的代码在用户输入值后使用setTimeout。如果输入了新密码,则取消超时。

我想确认下面的方法是否正确,因为清除超时后,它不会像异步验证功能“ test”所期望的那样返回Promise。

let timeout = null;
const validationSchema = Yup.object({
  name: Yup.string("Enter your name").required("Name is required"),
    .test("checkDuplUsername", "Username already taken", function(value) {
      clearTimeout(timeout);
      if (!value) return true;

      return new Promise((resolve, reject) => {
        timeout = setTimeout(async () => {

          let uname = value.trim().toLowerCase();
          let resp = await fetch('/check_username/' + value;

          resolve(resp.result.length === 0);
        }, 500);
      });
    })
})

1 个答案:

答案 0 :(得分:0)

您可以在超时后通过以下方式使用异步验证:

const validationSchema = Yup.object({
  name: Yup.string("Enter your name").required("Name is required")
  .test("checkDuplUsername", "Username already taken", function(value) {
    if (!value) {
      const isDuplicateExists = await checkDuplicate(value);
      console.log("isDuplicateExists = ", isDuplicateExists);
      return !isDuplicateExists;
    }
    // WHEN THE VALUE IS EMPTY RETURN `true` by default
    return true;
  }),
});

function checkDuplicate(valueToCheck) {
  return new Promise(async (resolve, reject) => {
    let isDuplicateExists;

    setTimeout(() => {
      // CHECK HERE FOR DUPLICATE
      if (valueToCheck === "test") {
        isDuplicateExists = true;
        resolve(isDuplicateExists);
      } else {
        isDuplicateExists = false;
        resolve(isDuplicateExists);
      }
    }, 3000)
  });
}