如何正确地等待javascript中异步函数的返回?

如何正确地等待javascript中异步函数的返回?,javascript,express,async-await,google-signin,Javascript,Express,Async Await,Google Signin,我目前正在开发一个带有React前端和Express后端的GoogleSign-in Auth应用程序,我目前正处于验证后端令牌的过程中。此流程的文档显示验证令牌的代码: const {OAuth2Client} = require('google-auth-library'); ... const client = new OAuth2Client(CLIENT_ID); async function verify() { const ticket = await client.ver

我目前正在开发一个带有React前端和Express后端的GoogleSign-in Auth应用程序,我目前正处于验证后端令牌的过程中。此流程的文档显示验证令牌的代码:

const {OAuth2Client} = require('google-auth-library');

...

const client = new OAuth2Client(CLIENT_ID);
async function verify() {
  const ticket = await client.verifyIdToken({
      idToken: token,
      audience: CLIENT_ID,  // Specify the CLIENT_ID of the app that accesses the backend
      // Or, if multiple clients access the backend:
      //[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]
  });
  const payload = ticket.getPayload();
  const userid = payload['sub'];
  // If request specified a G Suite domain:
  //const domain = payload['hd'];
}
verify().catch(console.error);
我在自己的项目中实现了以下代码:

//verify token
async function verify(token, client) {

  const ticket = await client.verifyIdToken({
    idToken: token,
    audience: keys.google.clientID,
  });

  const payload = ticket.getPayload();
  const userid = payload['sub'];
  const domain = payload['hd'];
  const email = payload['email']
  console.log('User ID: ' + userid);
  console.log('Domian: ' + domain);
  console.log('Email: ' + email);

  var message = '';
  var cookie = {};
  await User.find({email: email}, (error, user) => {
    if(error) {
      message = error;
    } else if (user.length === 0) {
      message = 'this user is not in the database';
    } else {
      message = 'this user is in the database';
      const session = new Session({
        email: email,
        session_token: token
      });
      cookie = {
        email: email,
        session_token: token
      };
      session.save((error, session) => {
        if (error) {
          console.log(error);
        } else {
          console.log('session saved');
        }
      });
      console.log(message);
    }
  });
  return Promise.resolve(cookie);
}

//recieve token id from frontend, verify it, and send session back in response
router.post('/google', (req, res) => {
  const body = req.body.tokenID;
  const client = new OAuth2Client(keys.google.clientID);

  let cookie = verify(body, client).catch(console.error);

  console.log('Cookie:' + cookie);
  return res.send(cookie);
});
当前,当它运行时,异步函数中的所有内容都会执行,但return语句只返回空的promise对象。我认为我错误地使用了
async
wait
,但我不知道如何正确地让函数等待验证令牌的所有工作,然后在返回之前更新数据库

不确定这是否有帮助,但当我调用路由时,我的控制台会给我以下输出:

(我从输出字段中取出了我的个人信息,但假设这些行实际上有gmail帐户信息)

。。。
Cookie:[对象承诺]
用户ID:
多米安:
电邮:
此用户在数据库中
保存的会话

谢谢你的阅读

您将异步/等待与基于回调的调用混合在一起。我不知道您正在使用的库的内部结构,但模式应该更像这样:

var cookie = {};
try{
    const user = await User.find({email: email});
    if (user.length === 0) {
        console.log('this user is not in the database');
    }
    else {
        console.log('this user is in the database');
        const session = new Session({
          email: email,
          session_token: token
        });

        try{
            await session.save();
            console.log('session saved');
        } catch(err){
            console.log(err);
        }
        return {
          email: email,
          session_token: token
        };
} catch(error){
    console.log(error);
}
因为“verify”函数是一个异步函数,所以在调用它之前应该添加“await”。要捕获错误,只需将其放置在try/catch中:

router.post('/google', async (req, res) => {
  const body = req.body.tokenID;
  const client = new OAuth2Client(keys.google.clientID);

  try {
    let cookie = await verify(body, client);
    console.log('Cookie:' + cookie);
    return res.send(cookie);
  } catch(error) {
    // handling error
    console.log(error);
    return res.send("error")
}
});


`

不能在异步函数之外添加wait,所以要使整个回调函数异步。我更新了我的代码。我使整个回调异步,它工作了!非常感谢。我实现了这个模式,但仍然返回一个空的promise对象
router.post('/google', async (req, res) => {
  const body = req.body.tokenID;
  const client = new OAuth2Client(keys.google.clientID);

  try {
    let cookie = await verify(body, client);
    console.log('Cookie:' + cookie);
    return res.send(cookie);
  } catch(error) {
    // handling error
    console.log(error);
    return res.send("error")
}
});