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> {
...
}
Added the ability for the
resultifyfunction to handle synchronous code without returning a promise.This will keep our function synchronous without having to make it asynchronous for no reason.
With current version
Use case:
Possible solution:
Create a second function exactly the same, which this time would not take a
MaybePromise<T>butT, and returnTdirectly.Current:
Possible solution: