Skip to content

Instantly share code, notes, and snippets.

@erdesigns-eu
Created November 14, 2024 10:00
Show Gist options
  • Save erdesigns-eu/36c26adf21241e508b6db2764d7e2633 to your computer and use it in GitHub Desktop.
Save erdesigns-eu/36c26adf21241e508b6db2764d7e2633 to your computer and use it in GitHub Desktop.
Utility function to create a promise, and return the promise + reject + resolve
type ResolvablePromise<Value = void> = {
promise: Promise<Value>;
resolve: (value: Value | PromiseLike<Value>) => void;
reject: (reason?: any) => void;
};
export function makeResolvablePromise<Value = void>(): ResolvablePromise<Value> {
let resolveFunction: (value: Value | PromiseLike<Value>) => void;
let rejectFunction: (reason?: any) => void;
// Create a promise and store its resolve and reject functions
const promise = new Promise<Value>((resolve, reject) => {
resolveFunction = resolve;
rejectFunction = reject;
});
// Ensure resolve and reject functions are initialized
if (!resolveFunction || !rejectFunction) {
throw new Error("Failed to initialize resolve and reject functions");
}
return {
promise,
resolve: resolveFunction,
reject: rejectFunction,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment