使用 lodash debounce return 一个承诺

Using lodash debounce to return a promise

使用 React、react-final-form 和 lodash debounce 函数我想验证用户名是否尚未被使用(该字段正在使用 react-final-form)。

我在将去抖功能 return 从获取请求中获取已解决的承诺时遇到问题。

我提供了以下 codesandbox link 来证明我的问题:

谁能告诉我为什么我的代码不起作用。

验证的入口点来自 this.isNameUnique 在

的验证属性中引用的调用

import React from "react";
import { Field, Form } from "react-final-form";
import { debounce } from "lodash";

class DemoForm extends React.Component {
  getIsNameUnique = name => {
    console.log("getIsNameUnique", name);

    // fake fetch request
    return async name => {
      const asyncResponse = await new Promise(resolve =>
        setTimeout(resolve({ name: true }), 1000)
      );
      console.log("async api response", asyncResponse);
      return asyncResponse;
    };
  };

  debounceCreativeName = name => {
    console.log("debounceCreativeName", name);
    return new Promise(resolve => {
      debounce(() => resolve(this.getIsNameUnique(name)), 2000);
    });
  };

  isNameUnique = async name => {
    const isNameAvailable = await this.debounceCreativeName(name);
    console.log("isNameAvailable", isNameAvailable);
    return isNameAvailable;
  };

  render() {
    return (
      <Form
        onSubmit={() => null}
        render={({ handleSubmit, reset, submitting, pristine, values }) => {
          return (
            <form onSubmit={handleSubmit}>
              <Field name="name" validate={this.isNameUnique}>
                {({ input, meta }) => {
                  return (
                    <input
                      style={{
                        display: "flex",
                        height: "40px",
                        fontSize: "24px"
                      }}
                      autoComplete="off"
                      {...input}
                      type="text"
                      placeholder="Enter the name"
                    />
                  );
                }}
              </Field>
            </form>
          );
        }}
      />
    );
  }
}

export default DemoForm;

sandbox 解决了您的问题。

你不应该在每个渲染器上创建一个新的去抖功能:

return new Promise(resolve => {
  debounce(() => resolve(this.getIsNameUnique(name)), 2000);
});

相反,你应该用去抖动包裹你的整个函数 isNameUnique(见我的沙盒)。通过在每次点击时创建一个新的去抖功能,它不能 'remember' 被调用或将被再次调用。这将防止去抖动。

此外,通过异步 getIsNameUnique 你可以降低它的复杂性,只需使用 await。