Created
August 30, 2023 12:17
-
-
Save thibmeu/f0f5f0301c37b79f741fa5d9032e8ae5 to your computer and use it in GitHub Desktop.
DON'T DO THIS. Block the thread to resolve a promise synchronously
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
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