如何从数据库异步获取数据?

时间:2018-11-05 17:09:59

标签: javascript node.js mongodb

我创建了两个用户之间的聊天应用程序。启动客户端时,将为用户1分配一个值,并且在开始时未定义user2。当用户单击屏幕快照左侧的用户列表按钮时,将分配user2。所以现在我有user1和user2,所以现在我想获取user1和user2之间的所有数据,但是得到一个空数组。单击后设置了user2后,如何调用conversation.find({ $and : [ { user1: user1 }, { user2: user2 } ] })

注意:conversation.find({})可以正常工作,但是conversation.find({ $and : [ { user1: user1 }, { user2: user2 } ] })无法正常工作。

下面的代码不起作用:

let conversation = db.collection('conversation'); 
  let user1,user2;

      socket.on('GET_USER', function (data) {
        console.log(data);
         user2 = data.user2;
      });

      socket.on('LOGGEDIN_USER', function(data) {
        console.log(data);
         user1 = data.user1;

         console.log("This is user1 "+ user1)
         console.log("This is user2 "+ user2)

         conversation.find({ $and : [ { user1: user1 }, { user2: user2 } ] }).toArray(function (err, res) {
          if(err){
              throw err;
          }

          console.log(res) 
              // Emit the messages
          io.emit('RECEIVE_MESSAGE', res);
        })

      });

屏幕截图:

enter image description here

聊天屏幕截图:

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以使用Promise s

let conversation = db.collection("conversation");
const waitForUser2 = new Promise((resolve, reject) => {
    socket.on("GET_USER", function (data) {
        resolve(data.user2);
    });
});
const waitForUser1 = new Promise((resolve, reject) => {
    socket.on("LOGGEDIN_USER", function (data) {
        resolve(data.user1);
    });
});
Promise.all([
    waitForUser1,
    waitForUser2
]).then(([user1, user2]) => {
    console.log("This is user1 " + user1);
    console.log("This is user2 " + user2);
    conversation.find({
        $and: [
            {user1: user1},
            {user2: user2}
        ]
    }).toArray(function (err, res) {
        if (err) {
            throw err;
        }
        console.log(res);
        // Emit the messages
        io.emit("RECEIVE_MESSAGE", res);
    });
});