socket.io和异步查询有问题

时间:2019-05-07 22:55:25

标签: node.js socket.io

我试图通过socket.io从数据库查询中传递信息,而我遇到的麻烦比我想象的要多。

这是socket.io发出的信号:

module.exports = (app, io) => {
  io.sockets.on('connect', async socket => {
    if (!socket.handshake.session.passport) {
      return socket.emit('redirect');
    }

    //Online
    console.log(Object.keys(app.online).length);
    //Load up
    await loadup(app, socket).then(data => {
      console.log(data);
    });
    await socket.emit('load up', loadup(app, socket));
}

(我尝试了多种方法来获取所需的数据以显示)

这是实际方法:

const statHandler = require('./loadhandling/statload');
const User = require('../models/User');
module.exports = async (app, socket) => {
  let isOnline = app.online[socket.handshake.session.passport.user];
  if (!isOnline) return;
  // Start the loadup process
  User.findById(socket.handshake.session.passport.user, (err, user) => {
    if (err) console.log(err);
    let userdata = user.meta;
    statHandler(userdata);
    return userdata;
  });
};

由于某些原因,我在这些情况下似乎总是很挣扎。

1 个答案:

答案 0 :(得分:0)

我设法弄糊涂了:

Socket.io

module.exports = (app, io) => {
  io.sockets.on('connect', async socket => {
    if (!socket.handshake.session.passport) {
      return socket.emit('redirect');
    }

    //Online
    console.log(Object.keys(app.online).length);
    //Load up
    const load = await loadup(app, socket);
    await socket.emit('load up', load);
}

方法:

const statHandler = require('./loadhandling/statload');
const User = require('../models/User');
module.exports = async (app, socket) => {
  let isOnline = app.online[socket.handshake.session.passport.user];
  if (!isOnline) return;
  // Start the loadup process
  const thisUser = await User.findById(
    socket.handshake.session.passport.user,
    (err, user) => {
      if (err) console.log(err);
    }
  ).then(user => {
    let userdata = user.meta;
    statHandler(userdata);
    return new Promise((res, rej) => {
      res({ userdata });
    });
  });

  return await thisUser;
};

我敢肯定有一种更有效的方法,但是我不想找到一个。希望这对以后的人有所帮助。