fun joker
fun joker

Reputation: 1727

How to get data asynchronously from database?

I have created a chat app between two users. When client is loaded user1 is assigned a value and user2 is undefined at start. When user clicks on user list button on left side in screenshot then user2 is assigned. So now I have user1 and user2 so now I want to get all the data between user1 and user2 but I get an empty array. How can I call conversation.find({ $and : [ { user1: user1 }, { user2: user2 } ] }) when user2 is set after click ?

Note: conversation.find({}) works fine but conversation.find({ $and : [ { user1: user1 }, { user2: user2 } ] }) is not working.

code below is not working:

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);
        })

      });

screenshot:

enter image description here

Chat screenshot:

enter image description here

Upvotes: 0

Views: 78

Answers (1)

ponury-kostek
ponury-kostek

Reputation: 8060

You can use Promises

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);
    });
});

Upvotes: 1

Related Questions