skip to Main Content

I am implementing a cli tool using bun. I have to collect inputs from user during runtime and I specifically need only one line from stdin. This is what I have implemented so far by referring the docs:

async function getInput() {
  for await (const input of console) {
    return input;
  }
}

async function liveTest() {
  /* some code here */
  console.log("input1:");
  await getInput();
  /* some code here */
  console.log("input2:");
  await getInput();
  /* some code here */
}

liveTest();

I am running it using bun file.js command. I am observing a problem where the input2 is not actually being collected. It just directly moves to the remaining code.

Can someone explain why and provide a fix/workaround?

2

Answers


  1. The problem is that you are restarting a for await loop on the same async iterator (console). This doesn’t work, because even if you exit the loop prematurely, the iterator is told to clean up (its return method is called). If you don’t intend to do your work in the body of the for await loop, then just call .next() on the async iterator, like this:

    async function getInput() {
      return (await console.next()).value;
    }
    
    Login or Signup to reply.
  2. you can use then()

    async function getInput() {
      for await (const input of console) {
        return console;
      }
    }
    
    async function liveTest() {
      /* some code here */
      console.log("input1:");
      getInput().then();
      /* some code here */
      console.log("input2:");
      getInput().then();
      /* some code here */
    }
    
    liveTest();
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search