Execute promises concurrently with a buffer pool size in Javascript
You can achieve this fairly easy using es6-promise-pool:
const tasks = [
(param) => new Promise(function(resolve, reject) {
setTimeout(resolve, 2000, 'foo');
}),
() => new Promise(function(resolve, reject) {
setTimeout(resolve, 2000, 'foo');
}),
() => new Promise(function(resolve, reject) {
setTimeout(resolve, 2000, 'foo');
}),
() => Promise.resolve(1),
() => Promise.resolve(2),
() => Promise.resolve(3)
];
let count = 1;
const promiseProducer = () => {
while(tasks.length) {
console.log('processing ' + count++);
const task = tasks.shift();
return task(); // optionally you could pass a parameter here
}
return null;
}
const pool = new PromisePool(promiseProducer, 3); // concurrent Promises set to 3
const poolPromise = pool.start();
poolPromise.then(() => { console.log('done!'); })
<script src="https://cdn.jsdelivr.net/npm/[email protected]/es6-promise-pool.min.js"></script>
I am just leaving my naive with generators implementation here! :)
function* myIteratorFactory(arr) {
for (let i = 0; i < arr.length; i++) {
yield(arr[i])
}
}
function delayPromise(text, ms) {
return function() {
return new Promise((resolve, reject) => {
console.log('[%s] Promise with value %s just started', new Date().toISOString(), text)
setTimeout(() => resolve(text), ms)
}).then(() => console.log('[%s] Promise with value %s just ended', new Date().toISOString(), text))
}
}
var promArr = [
delayPromise('hi', 1500),
delayPromise('alex', 2000),
delayPromise('how', 1700),
delayPromise('are', 1800),
delayPromise('you', 1500),
]
var que = 0
var myIterator = myIteratorFactory(promArr)
function executor(r) {
while (que < 3) {
var next = myIterator.next()
if (next.done) return;
next.value()
.then(() => {
que--
executor(r)
if (que == 0) r()
})
que++
}
}
executor(() => console.log('i am done for today!'))