Created
April 13, 2024 11:13
-
-
Save pantos27/9e235b9a3baaa10f74f01d50e5752716 to your computer and use it in GitHub Desktop.
A typescript way to use React Suspnse blocks with simple promises
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
const promiseWrapper = <T> (promise: Promise<T>): () => T => { | |
let status = "pending"; | |
let result: T; | |
const s = promise.then( | |
(value) => { | |
status = "success"; | |
result = value; | |
}, | |
(error) => { | |
status = "error"; | |
result = error; | |
} | |
); | |
return () => { | |
switch (status) { | |
case "pending": | |
throw s; | |
case "success": | |
return result; | |
case "error": | |
throw result; | |
default: | |
throw new Error("Unknown status"); | |
} | |
}; | |
}; | |
export default promiseWrapper; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on https://deadsimplechat.com/blog/react-suspense/