0

I am supposed to access a subcollection called 'followers' for a mobile user, this contains the id of the follower. Using this ID i should get data about the follower from the mobile_user collection and add it to an array. I can successfully iterate through the list of documents but when using push it seems like i'm unable to return the full list of data back out of the for loop.

Have a look at my current code:

Notice the two console logs, on the first one i can see the array getting filled with the information i want, on the second one the array it's returned empty. I'm definitely missing whatever is needed for the array to be returned out of the for loop. I am fairly new to js and any advice in the right direction would be appreciated.

const getFollowers = (data, context) => { 
    let id = data.id 
    const mobileUserRef = db.collection('mobile_user')

    return mobileUserRef.doc(id).collection('followers')
    .get()
    .then(function(doc) { 
        var result = []
         doc.forEach(function(follower) { 
            mobileUserRef.doc(follower.id).get()
            .then(function(followerdoc) { 
                result.push({
                    name: followerdoc.data().name
                })
                console.log(result)
            })
        })
        console.log(result)
        return result 
    })
  }
Luis
  • 305
  • 1
  • 14

1 Answers1

1

mobileUserRef.doc(follower.id).get() is asynchronous and returns immediately with a promise. The forEach loop will not wait for that promise to resolve before moving to the snapshot in the list. You should instead push that promise into an array, then use Promise.all on that array to wait for all the gets to complete before moving on. Then you will have to iterate each of those results and push them into another array to give to the caller.

See also:

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