Skip to content

Instantly share code, notes, and snippets.

@IAALAI
Created March 22, 2024 04:18
Show Gist options
  • Save IAALAI/b0348cbb1bdfd031c314e3898d72cefa to your computer and use it in GitHub Desktop.
Save IAALAI/b0348cbb1bdfd031c314e3898d72cefa to your computer and use it in GitHub Desktop.
js learn
export async function concurRequest(urls: string[], maxNum: number = 0) {
return new Promise((resolve, reject) => {
const results: any[] = urls;
if(urls.length === 0) {
resolve(results);
return;
}
let index = 0;
let runing_count = 0;
async function emit() {
let item_id = index;
console.log(item_id)
index++;
runing_count++;
if(item_id < urls.length) {
let res = await fetch(urls[item_id]);
results[item_id] = res;
runing_count--;
emit();
} else {
runing_count--;
if(runing_count == 1) {
resolve(results)
}
}
}
while(maxNum != 0 && runing_count < maxNum) //开始并发`
emit();
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment