Javascript 使用knex查询返回为未定义

Javascript 使用knex查询返回为未定义,javascript,database,backend,knex.js,Javascript,Database,Backend,Knex.js,我需要注册一个新用户,当接收到参数时,使用城市名称进行查询以获取州和城市id(两者都是外键)。我实现了一个查找ID的函数。在使用data.id的函数中,正确返回id。但在插入数据库时,正在插入“未定义” 显然,保存操作是在findCity和findState函数返回值之前执行的 cidade=城市,estado=城市 module.exports = app => { const obterHash = (senha, callback) => { bcry

我需要注册一个新用户,当接收到参数时,使用城市名称进行查询以获取州和城市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, (err, 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 }
}

我来自巴西,正在使用翻译,很抱歉拼写错误。

欢迎您来到异步世界

一般说明:您将在数据库查询发生之前使用它的结果。您的程序必须等待结果(
idCidade
idEstado
)才能使用它。因此,您可以在日志中找到将首先插入的记录

对于我将要使用的解释

函数findCidade(cidade){
返还承诺。决议(1);
}
函数findEstado(uf){
返还承诺。决议(1);
}
Promise.all([findCidade(),findEstado()]))
.然后((数据)=>console.log(数据));
输出为:

[1,1]
要解决此问题,您必须:

  • 使用
    Return
    语句显式返回承诺
  • Await
    通过
    async/Await
    Promise
    接口方法获取结果。或者使用
    回调
    ,如果它更适合您
  • module.exports=app=>{
    const obterHash=(senha,回调)=>{
    bcrypt.genSalt(10,(错误,盐)=>{
    bcrypt.hash(senha,salt,null,(err,hash)=>回调(hash))
    })
    };
    函数findCidade(cidade,){
    返回app.db('cidades')
    .where({nome:cidade})
    .first()
    。然后(数据=>{
    idCidade=data.id
    console.log('inside findCity.data.id:'+data.id)
    }).catch((err)=>console.log(“erro cidade”,err));
    }
    函数findEstado(uf){
    返回app.db('estados'))
    .where({uf:uf})
    .first()
    。然后(数据=>{
    idEstado=data.id
    console.log('insidefindstate.data.id:'+data.id)
    }).catch((err)=>console.log(“erro estado”,err));
    }
    常数保存=(请求、恢复)=>{
    控制台日志(“\n”);
    所有([findCidade(req.body.cidade),findEstado(req.body.uf)])
    。然后((数据)=>{
    常量[idCidade,idEstado]=数据;
    obterHash(req.body.senha,散列=>{
    const senha=散列;
    console.log(“将被插入。idCity:+idCidade+”idState:+idEstado”);
    app.db('salao')
    .插入({idcidade:idcidade,
    idestado:idestado,
    senha})
    .然后(=>res.status(200.send())
    .catch(err=>{res.status(400).json(err)})
    })
    })
    .catch((err)=>console.log(“一般错误”,err));
    };
    返回{save}
    }