Skip to content

Instantly share code, notes, and snippets.

@aztack
Last active May 8, 2024 07:35
Show Gist options
  • Save aztack/6957c2e6246463d459aa642b68bf7480 to your computer and use it in GitHub Desktop.
Save aztack/6957c2e6246463d459aa642b68bf7480 to your computer and use it in GitHub Desktop.
Wrap promise for React Suspense
export function readable<R, E = unknown>(
promise: Promise<R>,
onSuccess?: (result: R) => void,
onError?: (error: E) => void)
{
let status = 'pending';
let result: R;
const suspender = promise.then(result => {
status = 'fulfilled';
onSuccess && onSuccess(result);
result = result;
}, error => {
status = 'rejected';
onError && onError(error);
result = error;
});
return {
read() {
if (status === 'pending') {
throw suspender;
} else if (status === 'fulfilled') {
return result;
} else {
throw result;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment