将模块变量切换为实例变量

时间:2018-04-30 12:15:41

标签: javascript ecmascript-6 constructor

我创建了一个模块,用于并发async / await函数处理,类似于npm模块'async',只是没有回调。

我得到了它的工作:

module.exports = function () {
  module.internalQueue = []
  module.func = undefined
  module.parallelism =  1

  const process = async () => {
      const pickUpNextTask = () => {
        if (module.internalQueue.length) {
          return module.func(module.internalQueue.shift())
        }
      }
      const startChain = () => {
        return Promise.resolve().then(function next() {
          return pickUpNextTask().then(next)
        })
      }
      let chains = []
      for (let k = 0; k < module.parallelism; k += 1) {
        chains.push(startChain());
      }
      await Promise.all(chains)
      module.drain()
  }

  module.queue = (func, parallelism = 1) => {
    module.func = func
    module.parallelism = parallelism
    return module
  }

  module.push = async (customers) => {
    module.internalQueue.push(customers)
    await process()
  }

  module.drain = () => {}

  return module
}

我相信只有一个队列时我的解决方案才有效。如果有多个队列,则比赛将终止代码。

我试图将其重构为一个对象:

class async extends Object {
  constructor() {
    this.internalQueue = []
    this.propertyIsEnumerable = 1
    this.func = undefined
    this.drain = () => {}
  }

  static queue(func, parallelism = 1) {
    const o = new async.constructor()
    o.func = func
    o.parallelism = parallelism
    return o
  }

  async push(q) {
    this.internalQueue.push(q)
    await process()
  }

  async process() {
    const pickUpNextTask = () => {
      if (this.internalQueue.length) {
        return this.func(this.internalQueue.shift())
      }
    }
    const startChain = () => {
      return Promise.resolve().then(function next() {
        return pickUpNextTask().then(next)
      })
    }
    let chains = []
    for (let k = 0; k < this.parallelism; k += 1) {
      chains.push(startChain());
    }
    await Promise.all(chains)
    this.drain()
  }
}

是否有可能有一个静态方法来调用构造函数并返回对象?如果是,请分享指示。

谢谢

1 个答案:

答案 0 :(得分:0)

不要让它变得比它需要的更复杂。只需将值保留在局部变量中,而不是将它们放在class上。你不需要module.exports = function queue(func, parallelism = 1) { var internalQueue = [] async function process() { function pickUpNextTask() { if (internalQueue.length) { return func(internalQueue.shift()) } } async function startChain() { while (true) // I don't think this is what you want await pickUpNextTask(); } let chains = [] for (let k = 0; k < parallelism; k += 1) { chains.push(startChain()); } await Promise.all(chains) drain() } function drain() {} return async function push(customers) { internalQueue.push(customers) await process() // I don't think this is what you want } }

render() {
    return (
        <div className="box-2">
            <h2> Issues </h2>
            <Issues className="Iss" issues={this.state.issues} update_description={this.update_description}/>
        </div>
    );
}