代码之家  ›  专栏  ›  技术社区  ›  josemartindev

为什么我的变量没有改变它们的值?

  •  1
  • josemartindev  · 技术社区  · 6 年前

    我只是在为我的后端做一个get路由,我不明白为什么我的变量user和pass在console.log时仍然是假的。是否有其他方法/功能而不是findone来检查用户名和密码是否正确?

    app.get('/connect', (req, res) => {
        let user = false;
        let pass = false;
        User.findOne({login: req.query.login}).then((currentUser) => {
            if (currentUser)
                user = true;
        })
        User.findOne({password: req.query.password}).then((currentPassword) => {
            if (currentPassword)
                pass = true;
        })
        console.log(user); //prints still false
        console.log(pass); //prints still false
    });
    
    2 回复  |  直到 6 年前
        1
  •  3
  •   Fallenreaper    6 年前

    看来等待的是决议。

    如上所述,由于异步性质,它将触发这些请求并立即继续执行。这就是您的控制台将打印错误的原因,但在n次之后,它们实际上发生了更改。

    您可以通过说:

    async (a,b) => {}
    

    如果你用速记。然后,你可以说: await functioncall(); 对于Ant异步调用,您需要处理。

    请记住,如果您想等待某件事情,那么父函数需要是异步的。这才是真正的收获。

    要将它们放在一起,考虑到您的代码如下:

    app.get('/connect', async (req, res) => { // If you leverage await, you need to define parent function as async by a keyword.
        let user = false;
        let pass = false;
        //you tell this function to wait until it has fully finished its promise chain.
        await User.findOne({login: req.query.login}).then((currentUser) => {
            if (currentUser)
                user = true;
        })
        // Same as above
        await User.findOne({password: req.query.password}).then((currentPassword) => {
            if (currentPassword)
                pass = true;
        })
        console.log(user); //now will print true.
        console.log(pass); //now will print true.
    });
    

    我注意到上面的关键变化。

        2
  •  1
  •   Matty J    6 年前

    您需要使数据库搜索异步进行。您可以利用异步/等待来完成这一点。

    app.get('/connect', async (req, res) => {
    let user = false;
    let pass = false;
    
    const currentUser = await User.findOne({login: req.query.login});
    if (currentUser)
        user = true;
    
    const currentPassword = await User.findOne({password: req.query.password});
    if (currentPassword)
        pass = true;
    
    console.log(user);
    console.log(pass);
    });