Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
43
rated 0 times [  47] [ 4]  / answers: 1 / hits: 137272  / 8 Years ago, wed, november 16, 2016, 12:00:00

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 reasonably large number (in the thousands), and I would like to make sure I am not hitting a web server with thousands of concurrent HTTP requests.



An abbreviated version of this code currently looks something like this...



function getCounts() {
return users.map(user => {
return new Promise(resolve => {
remoteServer.getCount(user) // makes an HTTP request
.then(() => {
/* snip */
resolve();
});
});
});
}

Promise.all(getCounts()).then(() => { /* snip */});


This code is running on Node 4.3.2. To reiterate, can Promise.all be managed so that only a certain number of Promises are in progress at any given time?


More From » node.js

 Answers
27

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:


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)
})

[#60038] Monday, November 14, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kinsley

Total Points: 352
Total Questions: 84
Total Answers: 94

Location: Denmark
Member since Tue, Jul 19, 2022
2 Years ago
;