简体   繁体   English

表达异步/等待返回未定义

[英]express async/await returning undefined

I am working on an express app and trying to use asyn/await in my route.我正在开发一个快速应用程序并尝试在我的路线中使用 asyn/await。 Right now it doesnt seem to me waiting for the findOneUser call to return and is skipping to the next line:现在,在我看来,它似乎没有等待 findOneUser 调用返回,而是跳到下一行:

app.post ('/api/authenticate', async(req, res) => {
  console.log('GET TO AUTHENTICAE')
  const { email, password } = req.body;
  const user_db = await users.findOneUser( email );
  console.log("user_db", user_db)
  return user_db
});

 const findOneUser = (email) => {
    console.log("email", email)
     pool.query('SELECT * FROM users where email = $1', [email], (error, results) => {
      if (error) {
        throw error
      }
      console.log("RESULT", results.rows)
       results.rows
    })
  }

Here are my logs in the terminal, you can see the user_db_log is showing up before the RESULT log but my understanding of async/await is that the user_db code should have waited for the user.findOneUser method to run:这是我在终端中的日志,您可以看到 user_db_log 在 RESULT 日志之前显示,但我对 async/await 的理解是 user_db 代码应该等待 user.findOneUser 方法运行:

GET TO AUTHENTICAE获得认证

email example@outlook.com example@outlook.com示例@outlook.com

user_db undefined user_db未定义

RESULT 

[
  {
    id: 11,
    first_name: 'Test',
    last_name: 'User',
    email: 'testuser@test.com'
  }
]

try this way using Promise and async, await使用Promiseasync, await

 app.post ('/api/authenticate', async(req, res) => {
      console.log('GET TO AUTHENTICATE')
      const { email, password } = req.body;
      const user_db = await users.findOneUser(email);
      console.log("user_db", user_db)
      return user_db;
    });


 const findOneUser = async (email) => {
        var myPromise = () => {
            return new Promise((resolve, reject) => {
                pool.query('SELECT * FROM users where email = $1', [email], (error, results)=> {
                    error ? reject(error) : resolve(results);
                });
            });
        }
        var result = await (myPromise());
        return result;
  }

Await waits until the promise resolves. Await 等待 promise 解决。

But your findOneUser function is not returning promise and hence await immediately execute then returns.但是您的findOneUser function 没有返回 promise ,因此等待立即执行然后返回。

So to make it work either add async{adding async to a function returns response wrapped in a promise} to your findOneUser function or create a promise inside the same function then return the response wrapped in promise. So to make it work either add async{adding async to a function returns response wrapped in a promise} to your findOneUser function or create a promise inside the same function then return the response wrapped in promise.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM