如果我要做这件事,我会首先制作一个基于Promise的readLine问答函数版本:
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
关键字,以指示node在问题得到答案之前不要继续进行。此外,还需要注意的是,每当我们更改步骤时,你需要使用
return
关键字,以防止其他步骤运行。以下是完整的程序供你复制和测试:
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
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();
},
};
steps.start();