【问题标题】:How to wait for promise in a forEach in JavaScript? [duplicate]如何在 JavaScript 的 forEach 中等待 promise? [复制]
【发布时间】:2022-01-07 11:10:58
【问题描述】:

我想从我的 mongodb 集合中检索一个数组,然后在将它发送回客户端之前使用它。 我想要的结果如下:

  • 从collection_A中获取数组
  • 通过另一个 mongodb 查询,对我刚刚得到的数组进行所需的工作
  • 将数组传回客户端

我当前的代码如下所示:

                db.collection("collection")
                .find()
                .toArray()
                .then((arr) => {
                    arr.forEach(cur => {
                        db.collection("another-collection")
                            .count({key: cur.prop})
                            .then((retrieved) => {
                                cur.prop = retrieved; //The amount of count one live above
                                //This part runs later than the res.success below
                            })
                            .catch((err: any) => {
                                //Handle error
                            });
                    });
                    return arr;
                })
                .then(arr => {
                    res.success(arr);
                })
                .catch((err) => {
                    //Handle error
                });

目前,我想要对检索到的数组进行的工作发生在res.success() 之后,因此在客户端上我将获得原始数组。 为什么会这样?

【问题讨论】:

  • 我很确定这是同一个问题,但我不知道如何在我的代码中实现解决方案
  • 尝试使用for-of 而不是foreach

标签: javascript mongodb promise


【解决方案1】:

您可以将Promise.allArray#map 一起使用。

.then((arr) => 
    Promise.all(arr.map(cur => 
        db.collection("another-collection")
            .count({
                key: cur.prop
            })
            .then((retrieved) => {
                cur.prop = retrieved; 
                return curr;
            })
            .catch((err: any) => {
                //Handle error
            })
    ))
)

【讨论】:

  • 这样我成功发回的数组由于某些原因是未定义的
  • @D.Albert .thendb.collection(...) 之后有返回声明吗?如果没有,请添加 return curr 或您想要返回的任何内容。
  • 我不确定应该在哪个部分放置退货声明。你能在你的代码中演示一下吗?如果 Promise.all 使用设备返回一个 Promise,那么我想我应该把它放在 Promise.all 之后,但是我的 IDE 显示以下部分的代码无法访问。
  • @D.Albert 我已经更新了我的答案,但不清楚你想要返回什么结果。
  • 我想操作从第一个查询中获得的数组的每个元素,然后返回操作后的数组以将其发送回客户端
猜你喜欢
  • 2019-05-22
  • 2018-02-12
  • 1970-01-01
  • 2018-04-17
  • 2016-09-18
  • 2015-05-09
  • 2021-06-30
相关资源
最近更新 更多