Created
November 18, 2023 22:57
-
-
Save malerba118/d56f456049aeee4b11174ddd69f72664 to your computer and use it in GitHub Desktop.
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
import { action, makeObservable, observable, runInAction } from "mobx"; | |
export class PromiseManager<T extends (...args: any[]) => Promise<any>> { | |
status: "idle" | "pending" | "fulfilled" | "rejected" = "idle"; | |
executionCount = 0; | |
asyncFunction: T; | |
constructor(asyncFunction: T) { | |
makeObservable(this, { | |
status: observable.ref, | |
setStatus: action, | |
}); | |
this.asyncFunction = asyncFunction; | |
} | |
setStatus(status: "idle" | "pending" | "fulfilled" | "rejected") { | |
this.status = status; | |
} | |
get isPending() { | |
return this.status === "pending"; | |
} | |
get isFulfilled() { | |
return this.status === "fulfilled"; | |
} | |
get isRejected() { | |
return this.status === "rejected"; | |
} | |
execute = async (...args: Parameters<T>): Promise<ReturnType<T>> => { | |
const currentExecutionCount = this.executionCount + 1; | |
this.executionCount = currentExecutionCount; | |
this.setStatus("pending"); | |
try { | |
const result = await this.asyncFunction(...args); | |
// Check if this is the latest call | |
if (this.executionCount === currentExecutionCount) { | |
this.setStatus("fulfilled"); | |
return result as ReturnType<T>; | |
} else { | |
return Promise.reject(new Error("A newer call has been made")); | |
} | |
} catch (error) { | |
this.setStatus("rejected"); | |
return Promise.reject(error); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment