【问题标题】:Node Js Chaining the response节点 Js 链接响应
【发布时间】:2020-09-08 22:42:10
【问题描述】:

我正在尝试在循环中进行 db 调用,并希望将该数据添加到一个对象中,然后将该对象发送给用户,但我在用户端只得到一个空对象。 这个我已经查过了asynchronous response into a loop in javascript NodeJS

router.get('/collection', (req, res) => {
    const Data = {}

     Section.find({})
           .then(sections => {
             sections.map(section => {
                  let id = section._id;
                   Product.find({section: id})
                         .then(products => {
                           // console.log(products)
                            Data[section.title] = {
                                title: section.title,
                                routeName: section.title,
                                id,
                                items: products
                            }
                            console.log(Data)
                         })
                         .catch(err => {
                            return res.status(500).json(err)
                         })

              })
              return res.json(data)
           })
           .catch(err => {
               return res.status(500).json(err)
           })
})

我希望输出是这样的:-

{
  food : {
           items: [...]
         },
  vegetable: {
            items: [...]
             }
}

食物和蔬菜是键,将从数据库调用中获得,每个键中的项目从对数据库的单独调用中返回。

【问题讨论】:

    标签: node.js mongoose promise


    【解决方案1】:

    return res.json(data) 在解决任何映射的 Product-promise 之前执行(还有一个错字,因为您返回的是 data 而不是 Data)。一种方法是映射find-promises 并在映射数组上使用Promise.all。比如:

    router.get('/collection', (req, res) => {
        const Data = {}
    
        Section.find({})
        .then(sections => {
            const sectionProductPromises = sections.map(section => {
                let id = section._id;
                return Product.find({
                        section: id
                    })
                    .then(products => {                     
                        Data[section.title] = {
                            title: section.title,
                            routeName: section.title,
                            id,
                            items: products
                        }
                    });
    
            });
            return Promise.all(sectionProductPromises);    
        })
        .then(() => {
            res.json(Data)
        })
        .catch(err => {
            res.status(500).json(err)
        });
    });
    

    【讨论】:

    • 不,不要使用push!只需return 它,然后使用map() 调用的结果。
    • @Bergi:好点,我已经编辑了我的答案。感谢您的意见!
    • 你可以像这样直接在map函数上使用promise.allPromise.all(sections.map(section => {...})
    • @MahdiHashemi:是的,但我会保留它,因为我认为这样更易读。
    • @MahdiHashemi:我想我可以回答这个问题——使用 push 会不必要地增加空间复杂性,因为我们正在创建一个额外的数组。但是让我们看看 Bergi 是否还有其他观点:)
    猜你喜欢
    • 2017-09-24
    • 1970-01-01
    • 1970-01-01
    • 2015-08-19
    • 2021-01-03
    • 2018-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多