Last active
December 20, 2022 09:08
-
-
Save Fog3211/11658c81dc08b911278d4e8b3c5a06a5 to your computer and use it in GitHub Desktop.
[Control Concurrent requests by promise.race and all] 控制请求并发 #Typescript
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
| import axios from 'axios'; | |
| export const concurrentRequestRace = (urls: string[], max: number): Promise<unknown[]> => { | |
| return (async () => { | |
| const result: unknown[] = []; | |
| const pool: Promise<unknown>[] = []; | |
| if (urls.length === 0 || max <= 0) { | |
| return Promise.resolve(result); | |
| } | |
| const request = (currentIndex: number) => { | |
| const url: string = urls[currentIndex]; | |
| const req = axios | |
| .get(url) | |
| .then((res) => res.data) | |
| .then((res) => { | |
| result[currentIndex] = res; | |
| }) | |
| .catch((err) => { | |
| result[currentIndex] = err; | |
| }) | |
| .finally(() => { | |
| const index = pool.indexOf(req); | |
| pool.splice(index, 1); | |
| }); | |
| pool.push(req); | |
| }; | |
| for (let i = 0; i < urls.length; i++) { | |
| request(i); | |
| if (pool.length >= max) { | |
| await Promise.race(pool); | |
| } | |
| } | |
| await Promise.all(pool); | |
| return Promise.resolve(result); | |
| })(); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment