0

I'm trying to request data from an API in a foreach loop and push that data to an array and then return that array at the end. Here is my code:

db
            .collection('posts')
            .orderBy('createdAt', 'desc')
            .limit(10)
            .get()
            .then((data) => {
                let posts = [];
                data.forEach((doc) => {
                    db
                        .doc(`/users/${doc.data().userHandle}`)
                        .get()
                        .then((userDoc) => {
                            posts.push({
                                postId: doc.data().id,
                                userHandle: doc.data().userHandle,
                                userImageUrl: userDoc.data().imageUrl,
                                imageUrl: doc.data().imageUrl,
                            });
                        })
                })
                return res.json(posts);
            })
            .catch((err) => {
                console.error(err);
                res.status(500).json({ error: err.code});
            });

From this, the posts array return en empty array or object, even when i replace return res.json(posts) with

.then(() => {
return res.json(posts);
})

Any help is awesome!!!

1

1 Answer 1

2

The array is empty because by the time the response is sent, promises with posts are still pending resolution.

In order to fix this issue, you can collect all the promises in an array using .map(), wait for them to resolve with help of Promise.all() and send the response after that:

db
  .collection('posts')
  .orderBy('createdAt', 'desc')
  .limit(10)
  .get()
  .then((data) => {
    const promises = data.map((doc) => {
      return db
        .doc(`/users/${doc.data().userHandle}`)
        .get()
        .then((userDoc) => {
          return {
            postId: doc.data().id,
            userHandle: doc.data().userHandle,
            userImageUrl: userDoc.data().imageUrl,
            imageUrl: doc.data().imageUrl,
          };
        })
    });
    Promise.all(promises).then(posts => {
      res.json(posts);
    })
  })
  .catch((err) => {
    console.error(err);
    res.status(500).json({ error: err.code});
  });
Sign up to request clarification or add additional context in comments.

3 Comments

No luck with this, I still get returned an empty object with a 500 server error.
nevermind, .map wasn't working because i was supposed to call data.docs.map, thank you!!
@frankied003 Thanks for getting back to this, glad to know that the issue is resolved

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.