【问题标题】:Async-await not working as anticipated. Value is 'undefined' after using await异步等待未按预期工作。使用等待后值为“未定义”
【发布时间】:2019-08-31 04:11:13
【问题描述】:

我正在使用带有节点 js 的 socket.io。对于身份验证,我在 socket.io 中使用中间件,但代码没有等待中间件完成其工作,因此值为“未定义”。

这里是主要功能。

module.exports = async (server) => {

  const io = require('socket.io')(server);

  io.on(CONNECTION, async function (socket) {

      var email = await authenticateUser(io);
       console.log(email); // 'undefined'
      user = new User(email);
  });
}

中间件函数

async function authenticateUser(io) {

    io.use(async (socket, next) => {

        const handshakeData = socket.handshake.query;
        const token = handshakeData.token;

        const Email = await Token.isValid(token);

        console.log("Auth ---> " + Email); // here it is fine

        return new Promise((res, rej) => {
            if (Email) {
                res(Email);
            } else {
                rej();
            }
        });
    });
}

认证功能

exports.isValid = async (token) => {

    try {
        const decoded = jwt.verify(token, JWT_KEY);
        console.log(decoded.email) // here it is fine
        return decoded.email;
    } catch (error) {
        return false;
    }
}

谢谢!

【问题讨论】:

  • return Email;,无需在该箭头函数中返回承诺,因为它已被标记为 async/await 并且您已经在等待结果。
  • 避免将async functions 作为回调传递。您的 io.use 回调根本没有被承诺,authenticateUser 不会等待任何事情。另外,isValid 不应该是 async
  • @Bergi 是的,我尝试了很多东西,所以忘了从isValid 删除异步。但感谢您指出。

标签: javascript node.js async-await


【解决方案1】:

您在authenticateUser 中创建的promise 对调用者不可见,因为它是在您传递给io.use() 的函数范围内创建的。

相反,尝试创建更高一级词汇级别的 Promise,以便在完成 socket.io 事件处理程序后可见:

// middleware function
function authenticateUser(io) {
  return new Promise((resolve, reject) => {
    io.use(async (socket, next) => {

        const handshakeData = socket.handshake.query;
        const token = handshakeData.token;

        const Email = await Token.isValid(token);
            if (Email) {
                resolve(Email);
            } else {
                reject(); // should probably put an error here
            }
        });
    });
}

【讨论】:

    猜你喜欢
    • 2019-04-19
    • 2020-03-04
    • 2019-04-07
    • 2022-01-22
    • 2018-12-02
    • 1970-01-01
    • 2021-07-15
    • 2021-12-08
    • 1970-01-01
    相关资源
    最近更新 更多