【发布时间】: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