Last active
December 25, 2021 08:25
-
-
Save blackmiaool/58e14a70abe16b36ac1f99519110641c to your computer and use it in GitHub Desktop.
parallelTask
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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