Skip to content

Instantly share code, notes, and snippets.

@coding-chris-kao
Created August 8, 2019 04:07
Show Gist options
  • Save coding-chris-kao/a943f09dc8d21e9bd3bda0a791b31d56 to your computer and use it in GitHub Desktop.
Save coding-chris-kao/a943f09dc8d21e9bd3bda0a791b31d56 to your computer and use it in GitHub Desktop.
Chain async functions and execute once or repeat
class AsyncChain {
constructor() {
this.queue = []
}
funcA() {
this.queue.push(1000)
return this
}
funcB() {
this.queue.push(1500)
return this
}
execute(duration) {
return new Promise(resolve => {
setTimeout(() => {
console.log(duration)
resolve(this)
}, duration)
})
}
async once() {
for (const step of this.queue) {
await this.execute(step)
}
}
async repeat() {
let i = 0
while (true) {
const step = this.queue[i++]
await this.execute(step)
if (i == this.queue.length) i = 0
}
}
}
// main
const c = new AsyncChain()
c.funcA().funcB().repeat()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment