提问者:小点点

允诺。都有嵌套映射。。 第一个地图只工作其他返回空对象在猫鼬


允诺。都有嵌套映射。。 第一个映射只工作其他返回空对象在猫鼬节点我只使用一个承诺。所有扭曲两个映射

这个这个代码

let foundCategory = await Category.findOne({_id: req.params.id})
 let CategoryWithSections =  {...foundCategory.toObject(),sectionsOfCategory: 
      //this map work    
     await Promise.all( foundCategory.sectionsOfCategory.map(async(SOC)=>{
                let sections=  await Section.findOne({_id: SOC.sectionOfCategory })
                return {...sections.toObject(), productsOfSections: 
                 //this map doesn't work 
    sections.productsOfSection.map(async(POS)=>{
                         return await Product.findOne({_id: POS.productOfSection })
                    })
                  }
            // return await sections.filter((section) => section._id === SOC.sectionOfCategory)
        }) )   } 

共1个答案

匿名用户

ProductSofSections对象由Sections.ProductSofSection.Map填充,它是承诺数组。 因为你没有等待它,承诺不会立即解决。

等待Await总是绑定到它所在的最内部函数。 因此,await product.findone({_id:POS.ProductOfSection})仅绑定到异步(POS)=>{函数,而不是绑定到异步(SOC)=>{

如果您以类似的方式等待内部.map的所有承诺,那么它将创建“awaiting”链,该链将返回所有值

let foundCategory = await Category.findOne({
    _id: req.params.id
})
let CategoryWithSections = {
    ...foundCategory.toObject(),
    sectionsOfCategory:
        //this map work    
        await Promise.all(foundCategory.sectionsOfCategory.map(async (SOC) => {
            let sections = await Section.findOne({
                _id: SOC.sectionOfCategory
            })
            return {
                ...sections.toObject(),
                productsOfSections:
                    //this map doesn't work 
                    await Promise.all(sections.productsOfSection.map(async (POS) => {
                        return await Product.findOne({
                            _id: POS.productOfSection
                        })
                    }))
            }
            // return await sections.filter((section) => section._id === SOC.sectionOfCategory)
        }))
}

还需要指出的是,async函数只是表示该函数返回promise,然后您就可以处理这些promise了。 这意味着可以在没有await甚至没有async函数的情况下编写这部分内容,因为您返回的是promise,因此结果将是promises的数组,这是promise.all可以使用的内容

                await Promise.all(sections.productsOfSection.map((POS) => {
                    return Product.findOne({
                        _id: POS.productOfSection
                    })
                }))