【发布时间】:2019-06-19 20:46:54
【问题描述】:
这是我使用 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)
}
我喜欢它,但是不并行发出这么多请求会导致请求时间接近 3 秒。
所以,这是我没有 async/await 的丑陋解决方案,只是承诺:
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)
}
}
这不是很漂亮,但它可以在 200 毫秒内完成工作
我能有漂亮有效率吗?
【问题讨论】:
-
你可以用
await Promise.all(...)就好了。 -
这使它的丑陋减少了 2%