Skip to content

Instantly share code, notes, and snippets.

@eczn
Last active August 6, 2023 09:36
Show Gist options
  • Select an option

  • Save eczn/3a4418916fcc3015a4f91b529c9329f1 to your computer and use it in GitHub Desktop.

Select an option

Save eczn/3a4418916fcc3015a4f91b529c9329f1 to your computer and use it in GitHub Desktop.
use promise as a immutable state machine (一种将 Promise 当成状态机使用的实践,爷非常喜欢,只有用过或者遇到过类似逻辑的人才懂)
/** 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