You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中挂载到Promise的属性在Promise.all结果中丢失怎么办

问题原因

你把sizes属性挂载到了Promise实例对象上,但Promise.all返回的结果数组是所有输入Promiseresolve后的业务数据集合,和你之前传入的Promise实例没有关联,自然取不到挂载在Promise实例上的属性。

另外你的代码还存在笔误:挂载属性时写的是size,但你存储的规格数组属性名是sizes,即使挂载逻辑正确也会出现取值问题。

修复方案

调整prepareCategories逻辑,在每个分类创建Promise的then回调中,将返回的分类结果和对应sizes绑定后再返回,即可在Promise.all的结果中拿到关联好的数据:

const prepareCategories = (body) => {
    let category_promises = []

    for (let i = 0; i < body.categories.length; i++) {
        const categoryBody = body.categories[i]
        const currentSizes = categoryBody.sizes
        let object_category = {
           // 你的分类属性赋值逻辑
        }
        
        // 链式调用then,将分类结果和对应规格绑定后返回
        const categoryPromise = nmCategorySvcV2.create(object_category)
            .then(createdCategory => {
                return {
                    ...createdCategory,
                    sizes: currentSizes
                }
            })
        
        category_promises.push(categoryPromise)
    }
    
    return category_promises
}

后续调用Promise.all拿到的结果就会包含关联好的规格数据:

Promise.all(category_promises).then((categories) => {
    console.log(categories) 
    // 每个元素都包含创建完成的分类属性 + 对应的sizes规格数组,直接取分类id关联创建规格即可
})

内容的提问来源于stack exchange,提问作者Thyi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 16:06:06