Skip to content

Instantly share code, notes, and snippets.

@hectorguo
Created December 6, 2018 22:39
Show Gist options
  • Save hectorguo/9a117233ddcc3b982698d5ba094f1103 to your computer and use it in GitHub Desktop.
Save hectorguo/9a117233ddcc3b982698d5ba094f1103 to your computer and use it in GitHub Desktop.
Promise All with a max number of concurrent tasks
/**
* Run promise with a max number of concurrent tasks
* @param {Number} limit
*/
function promiseAllWithLimit(limit) {
let count = 0;
let queue = [];
const run = (fn, resolve, reject, ...args) => {
count++;
const promise = fn.apply(this, args);
return promise
.then((res) => {
count--;
if(queue.length > 0) {
queue.shift()();
}
resolve(res);
})
.catch(err => {
count--;
reject(err);
});
}
const helper = (fn, ...args) => {
return new Promise((resolve, reject) => {
if(count < limit) {
run(fn, resolve, reject, ...args);
} else {
queue.push(run.bind(this, fn, resolve, reject, ...args))
}
});
}
return helper;
}
// --------TEST--------
// each time only run 3 promise
// once there is a promise done, the next promise will be run immediately
var pl = pLimit(3);
const p = (duration) => {
return new Promise((resolve, reject) => {
console.log('Running', duration);
setTimeout(() => {
if(duration > 4) {
reject(duration);
return;
}
resolve(duration);
}, duration * 1000);
})
}
Promise.all([
pl(() => p(10)),
pl(() => p(5)),
pl(() => p(1)), // run first 3
pl(() => p(9)), // after that, run each by each
pl(() => p(6)),
pl(() => p(4)),
pl(() => p(1)),
pl(() => p(2)),
pl(() => p(10)),
])
.then(res => {
console.log('Promise all!!!!', res); // 'Promise all!!!!', [10, 5, 1, 9, 6, 4, 1, 2, 10]
})
.catch(err => {
console.error(err);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment