0

I am trying to make a chat app and using firestore and cloud functions. My firestore structure is

Users -> name,username,email,etc...
Conversations -> members:[memberId1,memberId2]

and when there is a new conversation created I am adding a conversation collection to Users/{memberId}/Conversation collection but either its not getting created or it takes long time to gets created

this is my cloud function to add Conversation info to Users collection

    functions.firestore
  .document('Conversations/{conversationId}')
  .onCreate((snapshot:any, context:any) => {
    const data = snapshot.data();
    const conversationId = context.params.conversationId;

    if (data) {
      const members = data.members;
      if(!Array.isArray(members)){
        console.log("Members is not an array")
        return null;
      } 
      for ( const member of members) {
        const currentUserId = member;
        const remainingUserIDs = members.filter((u:string) => u !== currentUserId);
        remainingUserIDs.forEach(async (m:string) => {
            return admin
            .firestore()
            .collection('Users')
            .doc(m)
            .get()
            .then((_doc) => {
              const userData = _doc.data();
              if (userData) {
                return admin
                  .firestore()
                  .collection('Users')
                  .doc(currentUserId)
                  .collection('Conversations')
                  .doc(m)
                  .create({
                    conversationId: conversationId,
                    image: userData.profilePic,
                    username: userData.username,
                    unseenCount: 0,
                    userId: m,
                  });
              }
              return null;
            })
            .catch((err) => { 
              console.log(err);
              return null;
             });
        });
      }
    }
    return null;

  });

and i see in the logs its gets called without error but no data getting added or it takes long to gets created. what am I doing wrong ? and another interesting thing is I have tested the function on emulator and it works fine but on production there is a problem

1 Answers1

0

Your code is not waiting for each of the promises in the foreach loop to resolve before returning from the overall function. The function is just returning null immediately. Calling then and catch on a promise doesn't make the code pause.

Your function must return a promise that resolves only after all other async work is finished. If you don't, the function will terminate early and clean up before the work is complete. This means you have to track all the promises that you kick off in the foreach loop. I suggest reading these to better understand the problem and get some ideas on how to manage this:

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441