Last active
May 8, 2024 07:35
-
-
Save aztack/6957c2e6246463d459aa642b68bf7480 to your computer and use it in GitHub Desktop.
Wrap promise for React Suspense
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
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