Skip to content
This repository has been archived by the owner on Jun 13, 2024. It is now read-only.

Ability for the resultify function to handle synchronous code #3

Open
Unarray opened this issue Nov 21, 2023 · 0 comments
Open

Ability for the resultify function to handle synchronous code #3

Unarray opened this issue Nov 21, 2023 · 0 comments

Comments

@Unarray
Copy link

Unarray commented Nov 21, 2023

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> {
  ...
}
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant