节点承诺属性
Node Promise properties
我正在开发一个导入器,我必须为每个类别创建类别及其大小,例如在此输入 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 的结果时,尺寸 属性 没有显示,只有实际创建的类别的属性。
我做错了什么?
您正在 promise 上设置 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
})
我正在开发一个导入器,我必须为每个类别创建类别及其大小,例如在此输入 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 的结果时,尺寸 属性 没有显示,只有实际创建的类别的属性。
我做错了什么?
您正在 promise 上设置 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
})