【问题标题】:Asynchronous property of JavaScript causing errorJavaScript 的异步属性导致错误
【发布时间】:2021-06-01 07:42:27
【问题描述】:

我在创建应用程序的注册页面时遇到问题。我有一个反应前端和一个节点/快递后端。我需要在反应中执行以下操作 -

  1. 对节点进行后端调用并检查用户是否存在
  2. 如果用户不存在,则对节点进行后端调用并将用户添加到数据库。

但是由于 JavaScript 的异步特性,在收到步骤 1 的响应之前,执行步骤 2。这会导致 MongoDB 表中出现重复条目​​。我曾尝试使用 .then() 函数但无法解决。可能是因为我以错误的方式使用了 .then() 吗?我该如何解决这个问题?

我对异步编程非常陌生,这很可能是一个新手错误。但请赐教。

由于是专有的,我也不能分享代码,希望你能理解。

更新: 我可以编写一个类似的场景。请看下面-

const addUser = (name, email, password, confirm, error, setError) => {
    setError('')
    if (name.length <= 0) {
        setError('Name can not be blank')
    }
    if (email.length <= 0) {
        setError('Email cannot be blank')
    }
    if (!email.includes("@")) {
        setError('Invalid email')
    }
    if (password.length <= 0) {
        setError('Password can not be blank')
    }
    if (password !== confirm) {
        setError('Passwords do not match')
    }

    fetch(`${host}check_user_exists`, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json' 
        },
        body: JSON.stringify({email: email})
    }).then(
        function(response) {
            console.log('response')
            return response.json()
        }
    ).then(
        function (result) {
            console.log('error')
            if(result.user === 'duplicate') {
                setError('User already exists')
                console.log(error)
                return error
            }
        }
    ).then(
        function (error) {
            console.log('add')
            if (error !== 'User already exists'){
                fetch(`${host}add_user`, {
                    method: 'POST',
                    headers: {
                        'Accept': 'application/json',
                        'Content-Type': 'application/json' 
                    },
                    body: JSON.stringify({
                        name: name,
                        email: email,
                        password: password
                    })
                })
            }
        }
    ).catch( 
        err => {
        console.log(err)
    })
}

提前致谢。

【问题讨论】:

标签: node.js reactjs express asynchronous fetch


【解决方案1】:

我建议在注册路径中使用中间件来检查用户/电子邮件是否已经存在,而不必发出两个不同的请求。但是,如果您仍然需要它们,因为您想实时进行验证,您可以尝试这样的事情:

const checkUser = async (username) => {
  await axios 
    .post(API_URL + "/auth/signUpCheck", {
      username: username,
    })
    .then(async (response) => {
      //response from API with value of check
      if (response) {
        return await "other axios post for add user";
      } else {
        //already exists
      }
    })
    .catch((error) => {
      throw error;
    });
};

或者在注册路由中使用中间件(后端):

checkDuplicateUsernameOrEmail = (req, res, next) => {
  // Username
  User.findOne({
    where: {
      username: req.body.username
    }
  }).then(user => {
    if (user) {
      res.status(400).send({
        message: "User already exists !"
      });
      return;
    }

    // Email
    User.findOne({
      where: {
        email: req.body.email
      }
    }).then(user => {
      if (user) {
        res.status(400).send({
          message: "Email already exists!"
        });
        return;
      }

      next();
    });
  });
};

【讨论】:

  • 感谢您的回复。我尝试了你提到的解决方案,它仍然无法正常工作。我在问题中添加了代码 sn-p。请检查,看看你是否可以提供帮助
猜你喜欢
  • 2020-04-13
  • 2016-07-29
  • 2018-06-29
  • 2015-12-09
  • 2015-11-02
  • 2018-09-28
  • 2020-04-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多