Last active
August 6, 2023 09:36
-
-
Save eczn/3a4418916fcc3015a4f91b529c9329f1 to your computer and use it in GitHub Desktop.
use promise as a immutable state machine (一种将 Promise 当成状态机使用的实践,爷非常喜欢,只有用过或者遇到过类似逻辑的人才懂)
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
| /** a way to use promise as an immutable state machine */ | |
| export class PromiseMachine<T> { | |
| /** this promise instance */ | |
| private $promise: Promise<T>; | |
| /** make this resolved */ | |
| private $resolve!: (val: T) => void; | |
| /** make this rejected */ | |
| private $reject!: (err: any) => void; | |
| /** 全部が終わった */ | |
| public isFrozen = false; | |
| /** construing a promise instance for this */ | |
| public constructor() { | |
| this.$promise = new Promise((resolve, reject) => { | |
| this.$resolve = resolve; | |
| this.$reject = reject; | |
| }); | |
| } | |
| /** isFrozen -> true (promise resolved) */ | |
| public resolve = (val: T) => { | |
| if (this.isFrozen) return; | |
| this.isFrozen = true; | |
| this.$resolve(val); | |
| } | |
| /** isFrozen -> true (promise rejected) */ | |
| public reject = (err: any) => { | |
| if (this.isFrozen) return; | |
| this.isFrozen = true; | |
| this.$reject(err); | |
| } | |
| /** map this machine to a promise instance */ | |
| public toPromise = () => this.$promise; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment