Skip to content

Instantly share code, notes, and snippets.

@hubgit
Created August 12, 2019 13:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hubgit/59c0defcb16ea3ffeb90b9f6e0a03b78 to your computer and use it in GitHub Desktop.
Save hubgit/59c0defcb16ea3ffeb90b9f6e0a03b78 to your computer and use it in GitHub Desktop.
A queue
type QueueItem = () => Promise<void>
export class Queue {
private items: QueueItem[] = []
private running: boolean = false
public add = (item: QueueItem): void => {
this.items.push(item)
if (!this.running) {
this.run()
}
}
private run = (): void => {
this.running = true
const item = this.items.shift()
if (item) {
item().finally(this.run)
} else {
this.running = false
}
}
}
@hubgit
Copy link
Author

hubgit commented Aug 12, 2019

Usage:

const queue = new Queue()

const request = <T extends any>(config: AxiosRequestConfig) => {
  return new Promise<AxiosResponse<T>>((resolve, reject) => {
    queue.add(() => axios.request<T>(config).then(resolve, reject))
  })
}

request({  url: 'https://example.com' }).then(response => console.log(response.data))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment