Inquirer.js icon indicating copy to clipboard operation
Inquirer.js copied to clipboard

Validate with ASYNC function causes missed input after several input attempts

Open kschang77 opened this issue 4 years ago • 1 comments

NOTE: This may be related to #845 and other similar issues. I'm relatively new to Github (despite having an account since 2015) so I apologize this is using the wrong etiquette.

I have a function that calls inquirer with an async validate function, because the results had to be pulled from a MySQL DB (verify the specified EmpID exists). It'd look something like this:

async function specialReport2() {
  try {
    const ans = await inquirer.prompt([
      {
        type: "input",
        name: "ID",
        message: "What ID to report on? "
        validate: someAsyncValidateFunction // see below
   }
    ])

    // queryStr = "" // not relevant
    // const db = makeDb(config);

    try {
      // res = await db.query(queryStr, ans.ID);

      console.log("Special Report 2 ran with " + ans.ID)

    } catch (err) {
      throw ("error in specialReport2 query ", err)
    } finally {
      // await db.close()
      return true
    }
  } catch (err) {
    throw ("error in specialReport2 inquirer ", err)
  }
}

async function someAsyncValidateFunction (str) {
  queryStr = "select * from employee where id = ?"
  const db = makeDb(config)
  try {
    res = await db.query(queryStr, str);
    // console.log("res ", res)
    if (res.length === 0) {
      return "Employee ID not found!";
    }
    return true;
  } catch (err) {
    throw ("error in validateEmployeeID " + str + " ", err)
  } finally {
    await db.close()
  }
}

I have a separate function implementing nested menus with inquirer.js. The "wireframe" menus work fine without any calls to inquirer with validations. But with validations, after a couple selections, with input calling the validate function, the input is de-sync'ed with the screen.

This does NOT happen if I stop using the validate function or use a validate function that is NOT async.


I had a hard time narrowing this down. I finally figured it out after rewriting the menu from scratch with a different syntax (I thought it was caused by a malformed .then so I rewrote everything in async/await, only to find something similar. I forgot to validate in some menu choices, and those worked perfectly. And I finally noticed the difference between the two versions. I went back to comment out the validate line in the old one, and it started working fine.

I'm not sure what's a good way to write a test case to illustrate this bug, as I've only really started programming in advanced JS and Node.js since March.

kschang77 avatar Apr 21 '20 02:04 kschang77