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

我需要注册一个新用户,当接收到参数时,请使用城市名称进行查询以获取州和城市ID(均为外键)。我实现了一个查找ID的函数。在使用data.id的函数中,正确返回了ID。但是在插入数据库时​​被“未定义”插入。

显然,在findCity和findState函数返回值之前,将执行保存操作。

execution flow

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 }
}

我来自巴西,正在使用翻译,对您的拼写错误感到抱歉。

youkuan 回答:使用knex将查询返回为未定义

欢迎您来到异步世界!

一般说明:您将在数据库查询结果发生之前使用它。您的程序必须等待结果(Protected Route<Route {...rest} render={ props=> (authTokens || localStorage.getItem("authTokens")) ? ( <Component {...props}/> ) : ( <Redirect to ={ { pathname: '/login',state: { from: props.location } } } /> )才能使用。因此,您可以在日志中首先找到记录idCidade

为便于解释,我将使用Minimal Reproducible Example

idEstado

输出为:

Will be inserted...

要解决此问题,您必须:

  1. 使用function findCidade(cidade) { return Promise.resolve(1); } function findEstado(uf) { return Promise.resolve(1); } Promise.all([findCidade(),findEstado()]) .then((data) => console.log(data)); 语句显式返回诺言。
  2. [ 1,1 ] 通过returnAwait接口方法获得的结果。或者,如果更适合您,请使用async/await
Promise
本文链接:https://www.f2er.com/3144056.html

大家都在问