首页 > 解决方案 > 在 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的数据,我的问题是:ProductCategory

标签: javascriptmongodbes6-promiserandom-seed

解决方案


推荐阅读