Created
August 8, 2019 04:07
-
-
Save coding-chris-kao/a943f09dc8d21e9bd3bda0a791b31d56 to your computer and use it in GitHub Desktop.
Chain async functions and execute once or repeat
This file contains 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
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