Open shfshanyue opened 1 year ago
在 graphql/loader 以及 trpc 中均有关于 batch 的实现,意在提升性能,将多次 IO 合并为一次 IO
其关键在于一次事件循环中的微任务队列存储所有的 batchKeys。
const batcher = (fn) => {
// todo batch logic
let allArgs = []
// 能够实现 batch 的关键所在
// 此处 fn(allArgs) 甚至可以实现为 fn([...new Set(allArgs)]),性能更好一些
const wait = Promise.resolve().then(() => fn(allArgs))
return async (args) => {
allArgs = [...allArgs, ...args]
const result = await wait
// allArgs 与 result 形成的一个 Map
// 借助于 lodash 可以更可读化地写成 Object.fromEntries(_.zip(allArgs, result))
const resultMap = result.reduce((acc, x, i) => {
const v = allArgs[i]
acc[v] = x
return acc
}, {})
return args.map(a => resultMap[a])
}
}
运行结果好像是输出 3 个 [3, 5, 7]
,返回的 promise
中 args
应该都指向了第一次调用时传入的参数
网上看到了另一种解法:SegmentFault
@MJWade96 已修复,并配上相应的注释、码上掘金的 Playground 以及相关源码参考。
补全及实现一下函数