Skip to content

Instantly share code, notes, and snippets.

@karol-majewski
Created September 20, 2023 21:26
Show Gist options
  • Save karol-majewski/7e13475b9c62c6eb415c4ea4308ac2bb to your computer and use it in GitHub Desktop.
Save karol-majewski/7e13475b9c62c6eb415c4ea4308ac2bb to your computer and use it in GitHub Desktop.
interface Response<T> {
status: 'success' | 'pending' | 'error';
data: T | null;
}
/**
* A promise tracker that will be updated
* when promise resolves or rejects
*/
const response: Response<unknown> = {
status: 'pending',
data: null
};
/**
* This is our suspender function
* that throws promise if it is not fulfilled yet
*/
export function suspend<T>(fn: () => Promise<T>) {
/**
* suspender is the promise we will throw
* so react can re-render when it is fulfilled
*/
const suspender = fn().then(
(res) => {
response.status = 'success';
response.data = res;
},
(error) => {
response.status = 'error';
response.data = error;
}
);
switch (response.status) {
case 'pending':
throw suspender;
case 'error':
throw response.data as T;
default:
return response.data as T;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment