【发布时间】:2021-06-01 07:42:27
【问题描述】:
我在创建应用程序的注册页面时遇到问题。我有一个反应前端和一个节点/快递后端。我需要在反应中执行以下操作 -
- 对节点进行后端调用并检查用户是否存在
- 如果用户不存在,则对节点进行后端调用并将用户添加到数据库。
但是由于 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)
})
}
提前致谢。
【问题讨论】:
-
请将您的代码作为文本发布在您的问题中。
-
如果由于专有原因无法共享代码,请创建一个最小可重现示例:stackoverflow.com/help/minimal-reproducible-example
-
大家好,我已经添加了代码 sn-p
标签: node.js reactjs express asynchronous fetch