Last active
May 8, 2022 17:22
-
-
Save fronterior/1d694b62502a2f330311d2ba9c0fa8c2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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