如果我要这样做,我会先创建一个基于 promise 的 readLine question 函数版本:
const question = (str) => new Promise(resolve => rl.question(str, resolve));
我会将其构建为一组步骤:
const steps = {
start: async () => {
return steps.seeCars();
},
seeCars: async () => {
const seeCars = await question("Would you like to see which cars are available? Please type yes/no: ");
if (seeCars === 'yes') { return steps.showCars(); }
if (seeCars === 'no') { return steps.locationSearch(); }
console.log('No worries, have a nice day');
return steps.end();
},
showCars: async () => {
console.log('showing cars');
return steps.end();
},
locationSearch: async () => {
const longlat = await question("Would you like to search by latitude or longitude instead? If yes, please type latitude and longitude: ");
return steps.end();
},
end: async () => {
rl.close();
},
};
如果您不熟悉异步函数,请注意您必须在问题前输入 await 以指示节点在问题得到答案之前不要继续。
另请注意,每当我们更改步骤时,您都需要return,以便该步骤的其余部分不会运行。
这里有完整的程序供你复制和玩:
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
// Create a promise based version of rl.question so we can use it in async functions
const question = (str) => new Promise(resolve => rl.question(str, resolve));
// A list of all the steps involved in our program
const steps = {
start: async () => {
return steps.seeCars();
},
seeCars: async () => {
const seeCars = await question("Would you like to see which cars are available? Please type yes/no: ");
if (seeCars === 'yes') { return steps.showCars(); }
if (seeCars === 'no') { return steps.locationSearch(); }
console.log('No worries, have a nice day');
return steps.end();
},
showCars: async () => {
console.log('showing cars');
return steps.end();
},
locationSearch: async () => {
const longlat = await question("Would you like to search by latitude or longitude instead? If yes, please type latitude and longitude: ");
return steps.end();
},
end: async () => {
rl.close();
},
};
// Start the program by running the first step.
steps.start();