Skip to content

Instantly share code, notes, and snippets.

@figloalds
Created July 27, 2019 18:16
Show Gist options
  • Save figloalds/1844826b46d44465132f0737781012fa to your computer and use it in GitHub Desktop.
Save figloalds/1844826b46d44465132f0737781012fa to your computer and use it in GitHub Desktop.
async asyncForEach(array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array);
}
}
async asyncParallelForEach(array, callback, nParallelism) {
nParallelism = Number(nParallelism);
if(!nParallelism || isNaN(nParallelism)) {
nParallelism = 4;
}
let newTasks = [];
let currentTasks = [];
let arrCopy = array.slice();
let returnVals = [];
let arrIdx = -1;
do {
while(newTasks.length + currentTasks.length < nParallelism && arrCopy.length > 0) {
let thisIdx = ++arrIdx;
let thisObj = arrCopy.shift();
let promise = new Promise(async res=> {
let result = {};
result.target = thisObj;
result.idx = thisIdx;
try {
let ret = await callback(thisObj, thisIdx);
result.retv = ret;
} catch(err) {
result.err = err;
}
promise.fulfiled = true;
res(result);
});
newTasks.push(promise);
}
while(newTasks.length) currentTasks.push(newTasks.shift());
let ret = await Promise.race(currentTasks);
returnVals.push(ret);
currentTasks = currentTasks.filter(t=> !t.fulfiled);
} while(arrCopy.length > 0 || currentTasks.length > 0);
returnVals = returnVals.sort((a,b)=> a.idx > b.idx ? 1 : b.idx > a.idx ? -1 : 0);
return returnVals;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment