简体   繁体   English

在 foreach 循环中调用异步 function 并在循环完成后返回数组

[英]Call an async function in foreach loop and return array once loop is done

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.我试图在 foreach 循环中从 API 请求数据并将该数据推送到一个数组,然后在最后返回该数组。 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由此,posts 数组返回 en 空数组或 object,即使我将 return res.json(posts) 替换为

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

Any help is awesome!!!任何帮助都很棒!!!

The array is empty because by the time the response is sent, promises with posts are still pending resolution.该数组是空的,因为在发送响应时,带有帖子的 Promise 仍在等待解决。

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:为了解决这个问题,您可以使用.map()收集数组中的所有承诺,等待它们在Promise.all()的帮助下解决,然后发送响应:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM