Skip to content
This repository was archived by the owner on Jun 13, 2024. It is now read-only.
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

@Unarray

Description

@Unarray

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

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions