如何根据用户回答终止Inquirer命令行交互式提示流程?
问题描述
我正在开发一款员工档案生成应用,采用递归式Inquirer交互流程,需要在交互的开头和末尾提供退出选项终止流程。目前设置了两个终止触发点:
- 选择「Finish building the team」选项
- 在「Do you want to add another employee?」问题中选择「否」
但这两个触发点都无法实现终止功能。
问题原因
- 当选择「Finish building the team」时,代码会继续执行后续的员工信息输入问题(姓名、ID、邮箱等),没有提前终止流程
- 即便完成所有问题后,代码依然会将终止选项的答案存入
employeesInfo,并且没有跳过递归调用
修复方案
需要在Inquirer的问题流程中加入判断,当用户选择终止选项时,直接结束当前prompt并终止递归;同时在递归函数中判断是否触发终止条件,不再继续调用自身。
修复后的代码如下:
const employeeQuestions = [ // Role of employee { type: 'rawlist', name: 'role', message: 'What is the role of the employee?', choices: [ 'Engineer', 'Intern', new inquirer.Separator(), 'Finish building the team', ], default: 3, }, // Employee questions - 仅当选择非终止角色时显示 { when(answer) { return answer.role !== 'Finish building the team'; }, type: 'input', name: `employee_name`, message: answer => `Enter name of the ${answer.role}`, }, { when(answer) { return answer.role !== 'Finish building the team'; }, type: 'number', name: `employee_id`, message: answer => `Enter ${answer.role} ID`, validate(answer) { const valid = !isNaN(parseFloat(answer)); return valid || 'Please enter a number'; }, filter: Number, }, { when(answer) { return answer.role !== 'Finish building the team'; }, type: 'input', name: `employee_email`, message: answer => `Enter ${answer.role} Email address`, }, // Engineer questions { when(answer) { return answer.role === 'Engineer'; }, type: 'input', name: `engineer_github`, message: 'Enter GitHub username', }, // Intern questions { when(answer) { return answer.role === 'Intern'; }, type: 'input', name: `intern_school`, message: 'Enter intern school', }, // add more employees - 仅当选择非终止角色时显示 { when(answer) { return answer.role !== 'Finish building the team'; }, type: 'confirm', name: `add_more`, message: 'Do you want to add another employee?', default: true, }, ]; // # Functions // * Inquires all over if add_more = true function inquireAgain() { inquirer.prompt(employeeQuestions).then(answers => { // 如果选择终止选项,直接输出结果并结束 if (answers.role === 'Finish building the team') { console.log(JSON.stringify(employeesInfo, null, ' ')); return; } // 仅当非终止选项时,存入员工信息 employeesInfo.push(answers); if (answers.add_more) { inquireAgain(); } else { console.log(JSON.stringify(employeesInfo, null, ' ')); } }); } // * Initialize the inquirer prompts async function init() { const inquireManager = await inquirer.prompt(managerQuestions); employeesInfo.push(inquireManager); inquireAgain(); } // # Initialisation init();
关键修改点
- 给所有员工信息输入问题和「add more」问题添加
when判断,仅当用户选择的角色不是「Finish building the team」时才显示 - 在
inquireAgain函数中,首先判断用户是否选择了终止选项,如果是则直接输出结果并返回,不再执行后续逻辑 - 确保终止选项的答案不会被存入
employeesInfo数组
内容的提问来源于stack exchange,提问作者Sagos
相关产品推荐
相关产品推荐

