简体   繁体   中英

Parallel processing of async/await functions queue

I am trying to process a queue, in parallel. I have an object array, and I need to apply function func to each element, in parallel. I am making the parallelism level of chains as below:

async function() {
  const pickUpNextTask = () => {
    if (this.internalQueue.length) {
      return this.func(this.internalQueue.shift())
    }
  }
  const startChain = () => {
    return Promise.resolve().then(function next() {
      console.log('before then(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()
}

It is not working like I want to. The pickUpNextTask() ends-up returning undefined when the queue is empty, so there is no then.

How does one deal with this?

Turned out, it was easy enough:

  const pickUpNextTask = () => {
    if (this.internalQueue.length) {
      return this.func(this.internalQueue.shift())
    } else {
      return Promise.reject()
    }
  }
  const startChain = () => {
    return Promise.resolve()
            .then(function next() {
              return pickUpNextTask()
                .then(next)
                .catch(() => {
                  return Promise.resolve()
                })
            })
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM