Skip to content

Instantly share code, notes, and snippets.

@thibmeu
Created August 30, 2023 12:17
Show Gist options
  • Save thibmeu/f0f5f0301c37b79f741fa5d9032e8ae5 to your computer and use it in GitHub Desktop.
Save thibmeu/f0f5f0301c37b79f741fa5d9032e8ae5 to your computer and use it in GitHub Desktop.
DON'T DO THIS. Block the thread to resolve a promise synchronously
const depromise = <T>(promise: Promise<T>): T => {
let result: T | undefined;
let error: Error | undefined;
let isPromisePending = true;
promise
.then((res) => {
result = res;
isPromisePending = false;
})
.catch((err) => {
error = err;
isPromisePending = false;
});
while (isPromisePending) {
// This loop blocks the thread, which is NOT recommended.
}
if (error) {
throw error;
} else {
if (!result) {
throw new Error();
}
return result;
}
};
const depromiseCallback = <T>(
callback: (...params: any[]) => Promise<T>,
): ((...params: any[]) => T) => {
return function (...params: any[]): T {
return depromise(callback(...params));
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment