0

I have an array of user Ids as 'members' passed into the getMemberAvatars() function. I take each id, look it up in the users collection, and put their photoURL in an array called memberAvatars. Once I have that array of URLS, I can pass JSX back using map. However, the memberArray of URLS is populated in a callback - so my JSX renders before it's back.

I need to wait for the result. Perhaps async/await can help? Other ideas?

 getMemberAvatars(members) {
    let memberAvatars = [];
    members.forEach(userId => {
      db.collection("users")
        .doc(userId)
        .get()
        .then(doc => {
          memberAvatars.push(doc.data().photoURL);
        });
    });
    return memberAvatars.map((url, index) => <Avatar src={url} />);
  }

Based on Doug's comments below, tried this to no avail....

 getPhotos(members) {
    let urls = [];
    for (let userId in members) {
      db.collection("users")
        .doc(userId)
        .get()
        .then(doc => {
          urls.push(doc.data().photoURL);
        });
    }
    return urls;
  }

  async getMemberAvatars(members) {
    let results = [];
    let urls = await this.getPhotos(members);
    await Promise.all(
      urls.map(async url => {
        results = await (<Avatar src={url} />);
      })
    );
    return results;
  }
ppedrazzi
  • 787
  • 2
  • 10
  • 23
  • 1
    This issue is not specific to Firebase. It applies to any situation where you have to iterate something with a lambda callback. The marked duplicate has a full discussion of your options. – Doug Stevenson Dec 24 '19 at 16:25
  • Thanks @DougStevenson - I read the above and am a bit lost. Can you help with my code above? I am not sure how to adjust it. – ppedrazzi Dec 24 '19 at 16:36
  • Collect all the promises into an array, then await the contents of that array after the forEach. There is an example of that in the duplicate. – Doug Stevenson Dec 24 '19 at 16:36
  • Thanks for the pointer @DougStevenson - I tried adapting that concept to what I'm doing - added to my question above - still can't make it work though. – ppedrazzi Dec 24 '19 at 17:27
  • This question is already closed as a duplicate. Please post your code in another question, and explain what it is doing that's different than what you expect. I will point out that getPhotos doesn't return a promise, so it can't really be awaited. https://stackoverflow.com/help/how-to-ask – Doug Stevenson Dec 24 '19 at 17:29
  • Thanks @DougStevenson - worked it out more and posted a new question for the error: https://stackoverflow.com/questions/59473492/using-async-await-in-firebase – ppedrazzi Dec 24 '19 at 21:22

0 Answers0