Skip to content

Instantly share code, notes, and snippets.

@kayac-chang
Created October 25, 2022 04:05
Show Gist options
  • Save kayac-chang/2a1de76e8c5a67789c75873506427649 to your computer and use it in GitHub Desktop.
Save kayac-chang/2a1de76e8c5a67789c75873506427649 to your computer and use it in GitHub Desktop.
using suspense for data fetching or any promise
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