Sar*_*ara 7 javascript if-statement input readline node.js
我试图readline在 else if 语句中使用:
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("Would you like to see which cars are available? Please type yes/no: ", function(answer) {
if (answer === 'yes') {
// if yes do something
} else if(answer === 'no') {
rl.question("Would you like to search by latitude or longitude instead? If yes, please type latitude and longitude: ");
} else {
console.log("No worries, have a nice day");
}
rl.close();
});
Run Code Online (Sandbox Code Playgroud)
如果用户键入“否”,向用户提出不同问题的正确方法是什么?
目前,如果用户键入否,则不会询问第二个问题。
如果我要这样做,我将首先制作 readLine 问题函数的基于承诺的版本:
const question = (str) => new Promise(resolve => rl.question(str, resolve));
Run Code Online (Sandbox Code Playgroud)
我会将它构建为一组步骤:
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();
},
};
Run Code Online (Sandbox Code Playgroud)
如果您不熟悉异步函数,请注意您必须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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9062 次 |
| 最近记录: |