Created
July 28, 2023 19:51
-
-
Save marcelitocs/d1d1da23e4929cd95200b385bf6d8b09 to your computer and use it in GitHub Desktop.
Map Concurrently
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
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