Home > other >  Node Promise properties
Node Promise properties

Time:11-11

I'm developing an importer, for each category i have to create the category and their sizes, for example in this input 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,
                    
                }
            ]
       }
   ]
}

but the problem is that sizes need to know the category id, so i'm trying to do it like this:

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)
                
            })

but when I see the result of Promise.all the sizes property is not displayed, only the properties of the category actually created.

what am i doing wrong?

CodePudding user response:

You are setting the size on the promise (which doesn't have any meaning). Instead you need to wait for the promise to be resolved and then set the size on its result:

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

(By the way you were missing a declaration for categoryPromise.)

The code could become a bit clearer using await syntax:

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
})
  • Related