Created
June 24, 2023 16:35
-
-
Save yarastqt/20e9d49dfce3528da622fcfdf44d31bb 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
export class Semaphore { | |
private concurrency: number | |
private currentCount: number | |
private queue: (() => void)[] | |
constructor(concurrency: number) { | |
this.concurrency = concurrency | |
this.currentCount = 0 | |
this.queue = [] | |
} | |
wait() { | |
return new Promise<void>((resolve) => { | |
const task = () => { | |
this.currentCount++ | |
resolve() | |
} | |
if (this.currentCount < this.concurrency) { | |
task() | |
} else { | |
this.queue.push(task) | |
} | |
}) | |
} | |
release() { | |
this.currentCount-- | |
if (this.queue.length > 0) { | |
const nextTask = this.queue.shift() | |
nextTask?.() | |
} | |
} | |
} | |
const semaphore = new Semaphore(3) | |
this.http = axios.create() | |
this.http.interceptors.request.use((config) => { | |
return semaphore.wait().then(() => { | |
return config | |
}) | |
}) | |
this.http.interceptors.response.use( | |
(response) => { | |
semaphore.release() | |
return response | |
}, | |
(error) => { | |
semaphore.release() | |
return Promise.reject(error) | |
}, | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment