如果我理解正确的话,可以说我有一个对象数组要保存到 Redis:
const processedStandings: Standings[] = processStandings(league, data)
for (const processedStanding of processedStandings){
await standingsRepository.save(processedStandings)
}
保存一堆对象的最佳方法是什么? 我看到一篇关于自动流水线的节点文章: https://www.npmjs.com/package/redis
这意味着我可以使用前提来做到这一点。所以类似:
const promises: Promise[] = {
return processedStandings.map(processedStanding => {
await standingsRepository.save(processedStandings)
})
}
const results: number[] = await Promise.all(promises);
但在这种情况下,我相信我只是并行执行请求。但没有完成自动流水线?
Node.js 的 Redis OM 也将进行管道操作。它只是利用了 Node Redis 在幕后所做的事情。您的代码很接近,但您不需要
await
调用 .save()
。只需返回 Promise
即可。
像这样:
const promises = processedStandings.map(processedStanding => {
return standingsRepository.save(processedStandings);
})
const results = await Promise.all(promises);
如果你真的想的话,你甚至可以在一行中得到它:
const results = await Promise.all(processedStandings.map(processedStanding => standingsRepository.save(processedStandings)));
虽然这可能有点多了。 😉