Skip to content

Instantly share code, notes, and snippets.

@marcelitocs
Created July 28, 2023 19:51
Show Gist options
  • Save marcelitocs/d1d1da23e4929cd95200b385bf6d8b09 to your computer and use it in GitHub Desktop.
Save marcelitocs/d1d1da23e4929cd95200b385bf6d8b09 to your computer and use it in GitHub Desktop.
Map Concurrently
function mapConcurrently(input, mapper, concurrency) {
let i = 0;
const result = [];
let pending = 0;
let done = false;
const promise = new Promise(function (resolve, reject) {
function startOne() {
if (done) return;
if (i == input.length) {
if (pending == 0) {
resolve(result);
}
return;
}
const item = input[i];
mapper(item).then(function (value) {
result.push(value);
pending--;
startOne();
}, function (error) {
done = true;
reject(error);
});
i++;
pending++;
if (pending < concurrency) {
startOne();
}
}
startOne();
});
promise.cancel = function () {
done = true;
}
return promise;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment