Skip to content

Instantly share code, notes, and snippets.

@yarastqt
Created June 24, 2023 16:35
Show Gist options
  • Save yarastqt/20e9d49dfce3528da622fcfdf44d31bb to your computer and use it in GitHub Desktop.
Save yarastqt/20e9d49dfce3528da622fcfdf44d31bb to your computer and use it in GitHub Desktop.
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