javascript - 在 Promise.all 期间创建随机数据
问题描述
我想创建一个基于 JSON 数组的模拟数据来测试前端。
JSON数组中的对象结构:
嘲笑:
{
category: string,
items: string[]
}
类别:
{
name: string,
products: Product[]
}
产品:
{
name: string,
prices: Price[]
}
价格:
{
date: Date,
value: number
}
我想Price
为每个创建随机 s Product
,因此我创建了以下辅助函数:
// Creates Price array with random values within a given time window
// `times` is a `lodash` function
const getRandomPrices = (numberOfDays, minValue, maxValue) => times(numberOfDays, n => ({
date: new Date(new Date().setDate(new Date().getDate() - n)),
value: Math.floor(Math.random() * maxValue) + minValue
}))
我正在使用以下功能为我的 MongoDB 数据库播种:
// data is Mock[]
// Price, Product and Category are MongoDB schemas
const createCategories = data.map(async c => {
const createProducts = c.items.map(async p => {
const prices = getRandomPrices(15, 100, 1000)
const createPrices = prices.map(price => Price.create(price))
return Product.create({
name: p,
prices: await Promise.all(createPrices)
})
})
return Category.create({
name: c.category,
products: await Promise.all(createProducts)
})
})
await Promise.all(createCategories)
console.log('done')
我的问题是我对任何任何一个都有相同Price
的数据,我的问题是:Product
Category
- 我怎样才能随机化价格?
- 我在哪里做错了?
解决方案
推荐阅读
- docker - Ubuntu systemd [1]:docker.service:作业 docker.service/start 失败,结果为“依赖”
- c# - 我尝试登录时出现 Cors 错误(WebApi+Blazor)
- python - 如何使用颜色对气泡图进行分类
- javascript - 嗨,我在使用 mongoose 删除保存在两个模式中的数据时遇到问题
- angular - 如何用新组件覆盖现有项目组件
- javascript - 如何解决这个 React-Router URL 参数错误?
- python - 如何在仍在执行脚本的同时清除 python 解释器?
- python - 使用python将嵌套的JSON对象转换为csv
- php - 在 TinyMCE 中保护 PHP
- flutter - 如何在谷歌地图中将文本设置为标记