Skip to content

3. Recipes

Jared Van Valkengoed edited this page Jul 15, 2024 · 5 revisions

Get answers in an object

When asking many questions, you might not want to keep one variable per answer everywhere.

In which case, you can put the answer inside an object.

const answers = {
  firstName: await term.input("What's your first name?"),
  allowEmail: await term.input('Do you allow us to send you email?'),
};

console.log(answers.firstName);

Ask a question conditionally

Maybe some questions depend on some other question's answer.

const allowEmail = await term.input("Can I have your email, if so say 'yes'")

let email;
if (allowEmail === 'yes') {
  email = await term.input('What is your email address');
}

Use Promises for sequential questions

Handle multiple questions sequentially using Promises.

const getAnswers = async () => {
  const firstName = await term.input("What's your first name?");
  const lastName = await term.input("What's your last name?");
  const age = await term.input("What's your age?");

  return { firstName, lastName, age };
};

getAnswers().then(answers => console.log(answers));
Clone this wiki locally