首页 > 解决方案 > 节点承诺属性

问题描述

我正在开发一个导入器,对于每个类别,我必须创建类别及其大小,例如在这个输入 JSON 中:

const input_json = {
"categories": [
        {
            
            "title": "category title",
            "sizes": [
                {
                    
                    "title": "size title",
                    "slices": 8,
                    "flavors": 4,
                    
                },
                {
                    "id" : "",
                    "title": "size title 2",
                    "slices": 8,
                    "flavors": 4,
                    
                }
            ]
       }
   ]
}

但问题是尺寸需要知道类别ID,所以我试图这样做:

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

    for (let i = 0; i < body.categories.length; i++) {
        const categoryBody = body.categories[i]

        let object_category = {
           ......
        } // set the object
        
        categoryPromise = nmCategorySvcV2.create(object_category) 
        
        categoryPromise.size = categoryBody.sizes

        category_promises.push(
            categoryPromise,
        )
    }
    
    return category_promises
}

......

          let category_promises = prepareCategories(input_json) // passing the input 

            Promise.all(category_promises).then((categories) => {
                console.log(categories)
                
            })

但是当我看到 Promise.all 的结果时,没有显示 size 属性,只有实际创建的类别的属性。

我究竟做错了什么?

标签: javascriptnode.jspromise

解决方案


您正在设置size承诺没有任何意义)。相反,您需要等待承诺得到解决,然后在其结果上设置大小:

const categoryPromise = nmCategorySvcV2.create(object_category)
 .then(result => Object.assign(result, { size: categoryBody.sizes }))

(顺便说一句,您缺少 . 的声明categoryPromise。)

使用await语法,代码可能会变得更清晰:

const prepareCategories = body => body.categories.map(async categoryBody => {
  const object_category = {
    //......
  } // set the object
  const categoryData = await nmCategorySvcV2.create(object_category)
  categoryData.size = categoryBody.sizes 
  return categoryData
})

推荐阅读