Skip to content

Instantly share code, notes, and snippets.

@codenamezjames
Created December 12, 2021 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codenamezjames/449930a7c9c6e532ca029bb0103373b2 to your computer and use it in GitHub Desktop.
Save codenamezjames/449930a7c9c6e532ca029bb0103373b2 to your computer and use it in GitHub Desktop.
export class ZQueue {
functions = []
autoRun = false
running = false
context = {}
constructor (config = {}) {
return this.options(config)
}
options (config = {}) {
if (typeof config.autoRun !== 'undefined') this.autoRun = !!config.autoRun
if (typeof config.context !== 'undefined') this.context = config.context
return this
}
push (fn) {
if (typeof fn !== 'function') throw new Error('Cannot add non-functions to the queue')
this.functions.push(fn)
if (this.autoRun) this.executeEach()
return this
}
async executeAll (context) {
if (this.running) return
this.options({ context })
this.running = true
const results = []
let i = -1
while (++i < this.functions.length) {
if (typeof this.functions[i] === 'function') results.push(Promise.resolve(this.functions[i].call(context)))
}
const all = await Promise.all(results)
this.running = false
return all
}
async executeEach (context) {
if (this.running) return
this.options({ context })
this.running = true
const results = []
for (const fn of this.functions) {
if (typeof fn === 'function') {
results.push(await Promise.resolve(fn.call(context)))
}
}
this.running = false
return results
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment