What is the best way to limit concurrency when using ES6's Promise.all()?

前端 未结 17 786
执念已碎
执念已碎 2020-11-29 21:28

I have some code that is iterating over a list that was queried out of a database and making an HTTP request for each element in that list. That list can sometimes be a rea

17条回答
  •  青春惊慌失措
    2020-11-29 21:51

    This is what I did using Promise.race, inside my code here

    const identifyTransactions = async function() {
      let promises = []
      let concurrency = 0
      for (let tx of this.transactions) {
        if (concurrency > 4)
          await Promise.race(promises).then(r => { promises = []; concurrency = 0 })
        promises.push(tx.identifyTransaction())
        concurrency++
      }
      if (promises.length > 0)
        await Promise.race(promises) //resolve the rest
    }
    

    If you wanna see an example: https://jsfiddle.net/thecodermarcelo/av2tp83o/5/

提交回复
热议问题