Skip to content

Instantly share code, notes, and snippets.

@blackmiaool
Last active December 25, 2021 08:25
Show Gist options
  • Save blackmiaool/58e14a70abe16b36ac1f99519110641c to your computer and use it in GitHub Desktop.
Save blackmiaool/58e14a70abe16b36ac1f99519110641c to your computer and use it in GitHub Desktop.
parallelTask
module.exports = async function parallelTask(task, shouldEnd, max) {
let i = 0;
let runningCnt = 0;
return new Promise((resolve, reject) => {
function check() {
if (shouldEnd(i)) {
return;
}
if (runningCnt > max) {
return;
}
const promise = task(i);
i++;
runningCnt++;
promise.then(() => {
runningCnt--;
check();
if (runningCnt === 0) {
resolve();
}
}).catch(function (e) {
reject(e);
})
check();
}
check();
});
}
module.exports = async function parallelTask<T>(
task: (index: number) => Promise<T>,
shouldEnd: (index: number) => boolean,
max: number
): Promise<T[]> {
let i = 0;
let runningCnt = 0;
return new Promise((resolve, reject) => {
const ret: T[] = [];
function check() {
if (shouldEnd(i)) {
return;
}
if (runningCnt > max) {
return;
}
const promise = task(i);
const index = i;
i++;
runningCnt++;
promise
.then(result => {
ret[index] = result;
runningCnt--;
check();
if (runningCnt === 0) {
resolve(ret);
}
})
.catch(function (e) {
reject(e);
});
check();
}
check();
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment