Skip to content

Instantly share code, notes, and snippets.

@fronterior
Last active May 8, 2022 17:22
Show Gist options
  • Save fronterior/1d694b62502a2f330311d2ba9c0fa8c2 to your computer and use it in GitHub Desktop.
Save fronterior/1d694b62502a2f330311d2ba9c0fa8c2 to your computer and use it in GitHub Desktop.
function asyncMap<T>(promiseFns: (() => Promise<T>)[], max: number) {
const result: T[] = [];
let count = 0;
let cursor = 0;
return new Promise(res => {
function run() {
while (count < max && cursor < promiseFns.length) {
count++;
const index = cursor++;
promiseFns[index]()
.then((value) => {
result[index] = value;
}, rej => console.log(rej))
.catch(err => console.error(err))
.finally(() => {
run();
count--;
if (!count) res(result);
});
}
}
run();
});
}
await async(Array(100).fill(async () => {
return new Promise(res => {
img = new Image;
img.onload = () => {
res();
console.log('load complete', img.src);
}
img.src = `https://picsum.photos/300/300?${Math.floor(Math.random() * 100 + 1)}`;
});
}), 5);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment