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

前端 未结 17 791
执念已碎
执念已碎 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条回答
  •  旧时难觅i
    2020-11-29 22:11

    Note that Promise.all() doesn't trigger the promises to start their work, creating the promise itself does.

    With that in mind, one solution would be to check whenever a promise is resolved whether a new promise should be started or whether you're already at the limit.

    However, there is really no need to reinvent the wheel here. One library that you could use for this purpose is es6-promise-pool. From their examples:

    // On the Web, leave out this line and use the script tag above instead. 
    var PromisePool = require('es6-promise-pool')
    
    var promiseProducer = function () {
      // Your code goes here. 
      // If there is work left to be done, return the next work item as a promise. 
      // Otherwise, return null to indicate that all promises have been created. 
      // Scroll down for an example. 
    }
    
    // The number of promises to process simultaneously. 
    var concurrency = 3
    
    // Create a pool. 
    var pool = new PromisePool(promiseProducer, concurrency)
    
    // Start the pool. 
    var poolPromise = pool.start()
    
    // Wait for the pool to settle. 
    poolPromise.then(function () {
      console.log('All promises fulfilled')
    }, function (error) {
      console.log('Some promise rejected: ' + error.message)
    })
    

提交回复
热议问题