Effect CommunityEC
Effect Community3y ago
9 replies
Pesticides

Understanding Effect and async code interaction

Hi, so I'm feeling a little lost with how Effect is supposed to interact with async code.

I simplified the problem that I'm working on to this regular async/await code. Basically the idea is to have 2 consecutive CLI prompts, where both of them will keep on repeating until user inputs some valid string (here, one that is not empty)
import { input } from "@inquirer/prompts";

// Get input text from user with Inquirer. `input` returns CancelablePromise<string>
const getInputAsync = (promptMessage: string) =>
  input({ message: promptMessage });

// String validation predicate
const checkIfIsLongerThan0 = (str: string): Boolean => str.length > 0;

const getInputUntilIsLongerThan0 = async (
  promptMessage: string
): Promise<string> => {
  const input = await getInputAsync(promptMessage);
  return checkIfIsLongerThan0(input)
    ? input
    : getInputUntilIsLongerThan0(promptMessage);
};

const mainAsyncWithoutEffect = async () => {
  const stringFromUser1 = await getInputUntilIsLongerThan0(
    "What's your user name?"
  );
  console.log(`Name: is ${stringFromUser1}`);

  const stringFromUser2 = await getInputUntilIsLongerThan0(
    "What's your email adress?"
  );
  console.log(`Email is: ${stringFromUser2}`);
};

mainAsyncWithoutEffect();

Previously I worked with fp-ts and having these 2 awaitable calls caused issues as well
I tried to model this with the use of Effect and the idea is simple: pipe the initial string, validate it creating Option.Option<string>, if it's not okay then do a recursive call in the function and ask user for new input. Then get another string the same way, and afterwards operate on these 2 values.

I managed to make it work so that it works for one user's input, but when I'm trying to implement it for 2 consecutive prompts, the best I could do was either
a) having the prompts appear on the screen at the same time, causing errors
b) introducing async/await calls inside of the Effect but it seems that it doesn't want to work ok
Was this page helpful?