Last active
April 2, 2024 19:43
-
-
Save HugoGresse/53bc0f553cb4ef57699d60023b67a20e to your computer and use it in GitHub Desktop.
Run many operations in parallel on a single array. Example: downloading 10 files by 10 files from a 1000 urls input
This file contains 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
const runInParallel = async (dataList, numberOfParallelRequest, runFunction) => { | |
return new Promise((resolve) => { | |
const isRunCompleted = (runStatus) => { | |
return Object.values(runStatus).every(status => status === false) | |
} | |
const dataListSplit = splitArray(dataList, numberOfParallelRequest) | |
console.log('dataListSplit', dataListSplit.length) | |
const runStatus = {} | |
dataListSplit.forEach(async (data, index) => { | |
runStatus[index] = true | |
const length = data.length | |
let i = 1 | |
for (const dataEl of data) { | |
await runFunction(dataEl) | |
console.log(`Run: ${index}: ${i}/${length}`) | |
i++ | |
} | |
runStatus[index] = false | |
console.log("- " + index + " ended") | |
if (isRunCompleted(runStatus)) { | |
resolve() | |
} | |
}) | |
}) | |
} | |
function splitArray(dataList, numberOfParallelRequest) { | |
const result = [] | |
const chunkSize = Math.ceil(dataList.length / numberOfParallelRequest) | |
for (let i = 0; i < dataList.length; i += chunkSize) { | |
result.push(dataList.slice(i, i + chunkSize)) | |
} | |
return result | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
possible improvement :