Last active
May 22, 2022 04:41
-
-
Save felds/c1f4645e36aa32edd1e22b12765978f1 to your computer and use it in GitHub Desktop.
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
type SuspendStatus = "pending" | "success" | "error"; | |
export function suspend<T>(promise: Promise<T>) { | |
let result: T; | |
let error: Error; | |
let status: SuspendStatus = "pending"; | |
let suspender = promise.then( | |
(r) => { | |
status = "success"; | |
result = r; | |
}, | |
(e) => { | |
status = "error"; | |
error = e; | |
}, | |
); | |
return { | |
read() { | |
switch (status) { | |
case "pending": | |
throw suspender; | |
case "error": | |
throw error; | |
default: | |
return result; | |
} | |
}, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment