Created
October 25, 2022 04:05
-
-
Save kayac-chang/2a1de76e8c5a67789c75873506427649 to your computer and use it in GitHub Desktop.
using suspense for data fetching or any promise
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
type PromiseState = "initial" | "pending" | "success" | "error"; | |
export function wrapForSuspense<Task extends (...args: any[]) => Promise<any>>( | |
task: Task | |
) { | |
let status: PromiseState = "initial"; | |
let result: Awaited<ReturnType<Task>>; | |
let suspend: Promise<void>; | |
return (...args: Parameters<Task>) => { | |
if (status === "initial") { | |
status = "pending"; | |
suspend = task(...args) | |
.then((res) => { | |
status = "success"; | |
result = res; | |
}) | |
.catch((err) => { | |
status = "error"; | |
result = err; | |
}); | |
} | |
if (status === "pending") { | |
throw suspend; | |
} | |
if (status === "error") { | |
throw result; | |
} | |
return result; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment