我需要注册一个新用户,当接收到参数时,请使用城市名称进行查询以获取州和城市ID(均为外键)。我实现了一个查找ID的函数。在使用data.id的函数中,正确返回了ID。但是在插入数据库时被“未定义”插入。
显然,在findCity和findState函数返回值之前,将执行保存操作。
cidade =城市,estado =城市
module.exports = app => {
const obterHash = (senha,callback) => {
bcrypt.genSalt(10,(err,salt) => {
bcrypt.hash(senha,salt,null,hash) => callback(hash))
})
}
var idCidade;
var idEstado
function findCidade(cidade,) {
app.db('cidades')
.where({ nome: cidade })
.first()
.then(data => {
idCidade = data.id
console.log('inside findCity. data.id: '+data.id)
}).catch((err) => console.log("erro cidade",err));
return
}
function findEstado(uf) {
app.db('estados')
.where({ uf: uf })
.first()
.then(data => {
idEstado = data.id
console.log('inside findState. data.id: '+data.id)
}).catch((err) => console.log("erro estado",err));
}
const save = (req,res) => {
console.log("\n")
findCidade(req.body.cidade)
findEstado(req.body.uf)
obterHash(req.body.senha,hash => {
const senha = hash
console.log("Will be inserted. idCity: "+idCidade+" idState: "+idEstado)
app.db('salao')
.insert({ idcidade: idCidade,idestado: idEstado,senha})
.then(_ => res.status(200).send())
.catch(err =>{res.status(400).json(err)})
})
}
return { save }
}
我来自巴西,正在使用翻译,对您的拼写错误感到抱歉。