Here is my pretty code using await/async
monthlyBuckets(req, res) {
const monthlyBuckets = []
const now = DateTime.local()
let date = config.beginningOfTime
while (date < now) {
monthlyBuckets.push({
epoch: date.toMillis(),
month: date.month,
year: date.year,
actions: await redis.get(`actions_monthly_${date.year}_${date.month}`),
interested: await redis.scard(`sinterested_monthly_${date.year}_${date.month}`),
adventurous: await redis.scard(`sadventurous_monthly_${date.year}_${date.month}`),
active: await redis.scard(`sactive_monthly_${date.year}_${date.month}`),
})
date = date.plus({month: 1})
}
res.status(200).json(monthlyBuckets)
}
I like it, but making so many requests not in parallel leads to a request time close to 3 sec.
So, here is my ugly solution without async/await, just promises:
monthlyBuckets(req, res) {
const monthlyBuckets = []
const actions = []
const interested = []
const adventurous = []
const active = []
const now = DateTime.local()
let date = config.beginningOfTime
let entryCount = 0
while (date < now) {
monthlyBuckets.push({
epoch: date.toMillis(),
month: date.month,
year: date.year,
})
actions.push(redis.get(`actions_monthly_${date.year}_${date.month}`))
interested.push(redis.scard(`sinterested_monthly_${date.year}_${date.month}`))
adventurous.push(redis.scard(`sadventurous_monthly_${date.year}_${date.month}`))
active.push(redis.scard(`sactive_monthly_${date.year}_${date.month}`))
date = date.plus({month: 1})
entryCount++
}
const data = await Promise.all(actions.concat(interested).concat(adventurous).concat(active))
for (let i = 0; i < entryCount; i++) {
monthlyBuckets[i].actions = data[i]
monthlyBuckets[i].interested = data[entryCount + i]
monthlyBuckets[i].adventurous = data[entryCount * 2 + i]
monthlyBuckets[i].active = data[entryCount * 3 + i]
}
res.status(200).json(monthlyBuckets)
}
}
That ain't pretty, but it gets the job done under 200ms
Can I have pretty and efficient?