This repository was archived by the owner on Jun 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
This repository was archived by the owner on Jun 13, 2024. It is now read-only.
Ability for the resultify function to handle synchronous code #3
Copy link
Copy link
Open
Description
Added the ability for the resultify
function to handle synchronous code without returning a promise.
This will keep our function synchronous without having to make it asynchronous for no reason.
const myFunction = (value: string): string => {
if (value.length < 4) throw new Error("Value is too short!")
// Perform operations on the value 🤷♂️
return value
}
const mySyncFunction = (value: string): string => {
const result = resultify(() => myFunction(value));
if(!result.ok) return "hello!";
return result.value
}
// For exemple, i can use my function at top-level
console.log(mySyncFunction ("hey"));
With current version
const myFunction = (value: string): string => {
if (value.length < 4) throw new Error("Value is too short!")
// Perform operations on the value 🤷♂️
return value
}
const myAsyncFunctionButItIsSync = async(value: string): Promise<string> => {
const result = await resultify(() => myFunction(value));
if(!result.ok) return "hello!";
return result.value
}
// For example, I can't use my theoretically synchronous function at the top-level
(async() => {
console.log(await myAsyncFunctionButItIsSync("hey"));
})();
Use case:
type MyFooObject = {
barMethod: (callback: (value: string) => string) => void;
};
const fooObject: MyFooObject;
fooObject.barMethod((value) => {
const myOperation = resultify(() => something(value));
if (!myOperation.ok) {
return 'a return example';
}
return myOperation.value;
});
// return type of `MyFooObject.barMethod` doesn't match `Promise<string>`
Possible solution:
Create a second function exactly the same, which this time would not take a MaybePromise<T>
but T
, and return T
directly.
Current:
export async function resultify<T>(fn: (...params: unknown[]) => MaybePromise<T>): Promise<Result<T, Error>> {
...
}
Possible solution:
export async function syncResultify<T>(fn: (...params: unknown[]) => T): Result<T, Error> {
...
}
Metadata
Metadata
Assignees
Labels
No labels