Created
April 1, 2019 07:22
-
-
Save dominikkaegi/64768ebca03913740d12d6372d090143 to your computer and use it in GitHub Desktop.
Structuring a class so that you can call async chained functions on the instantiation of it.
This file contains hidden or 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
| // Something to think about from this post :) | |
| // https://stackoverflow.com/questions/55413162/how-to-use-function-chaining-with-async-function?noredirect=1#comment97547907_55413162 | |
| class Walker { | |
| constructor(t) { | |
| this.t = t; | |
| // set up a task queue for chaining | |
| this.task = Promise.resolve(); | |
| } | |
| // shedules a callback into the task queue | |
| addTask(cb) { | |
| // TODO: error handling | |
| this.task = this.task.then(cb); | |
| return this | |
| } | |
| // allows to use this like a promise, e.g. "await walker"; | |
| then(cb) { cb(this.task); } | |
| goToMainPage () { | |
| this.doTask(async () => { // shedule to chain | |
| console.log("goToMainPage started"); | |
| await new Promise(res => setTimeout(res, 1000)); | |
| console.log("goToMainPage done"); | |
| }); | |
| return this; | |
| } | |
| } | |
| (async function() { | |
| const walker = new Walker; | |
| console.log("start tests"); | |
| await walker.goToMainPage(); | |
| console.log("one done"); | |
| await walker.goToMainPage().goToMainPage(); | |
| console.log("two done"); | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment