Async/Await Syntax
What advanced concept does concurrentMap implement?
async function sequentialMap(array, asyncFn) {
const results = [];
for (const item of array) {
results.push(await asyncFn(item));
}
return results;
}
async function concurrentMap(array, asyncFn, concurrency = 3) {
const results = new Array(array.length);
const executing = new Set();
async function execute(index) {
const item = array[index];
executing.add(index);
try {
results[index] = await asyncFn(item);
} finally {
executing.delete(index);
}
}
let index = 0;
while (index < array.length) {
if (executing.size < concurrency) {
execute(index++);
} else {
await Promise.race(Array.from(executing).map(
i => results[i]
));
}
}
return results;
}