Code Monkey home page Code Monkey logo

Comments (4)

shfshanyue avatar shfshanyue commented on May 27, 2024 2

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])
  }
}

from daily-question.

MJWade96 avatar MJWade96 commented on May 27, 2024 1

运行结果好像是输出 3 个 [3, 5, 7],返回的 promiseargs 应该都指向了第一次调用时传入的参数

from daily-question.

MJWade96 avatar MJWade96 commented on May 27, 2024 1

网上看到了另一种解法:SegmentFault

from daily-question.

shfshanyue avatar shfshanyue commented on May 27, 2024 1

@MJWade96 已修复,并配上相应的注释、码上掘金的 Playground 以及相关源码参考。

from daily-question.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.