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

前端 未结 17 767
执念已碎
执念已碎 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:54

    bluebird's Promise.map can take a concurrency option to control how many promises should be running in parallel. Sometimes it is easier than .all because you don't need to create the promise array.

    const Promise = require('bluebird')
    
    function getCounts() {
      return Promise.map(users, user => {
        return new Promise(resolve => {
          remoteServer.getCount(user) // makes an HTTP request
          .then(() => {
            /* snip */
            resolve();
           });
        });
      }, {concurrency: 10}); // <---- at most 10 http requests at a time
    }
    

提交回复
热议问题