javascript - 节点承诺属性
问题描述
我正在开发一个导入器,对于每个类别,我必须创建类别及其大小,例如在这个输入 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 属性,只有实际创建的类别的属性。
我究竟做错了什么?
解决方案
您正在设置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
})
推荐阅读
- bash - 以覆盖模式在 Bash 中打开文件描述符
- php - 如何在mysql登录过程中使用布尔值
- javascript - 如何在浏览器上下文中执行 Node.js 代码?
- go - 云扳手 IAM 权限被拒绝
- ios - 如何在 UIStackView 中等间距标签?
- ruby-on-rails - Rails 类方法用作具有复杂逻辑的作用域
- java - 如何在java中的for循环内多次执行if条件而不中断?
- mysql - 图像数组上的 Laravel 内爆函数
- javascript - React Router:重新路由时如何保持登录数据(道具)
- python - 如何在 Python 中将任意变量设置为全局变量?