我是一名C开发人员,正在尝试学习TypeScript(不了解JS\Node等,只学习C和一些C++)。我正在尝试从stdin中读取几行代码,但无法做到这一点……该怎么做呢?也许有人知道C-developer学习TS\JS的方法。因为现在我不能理解所有这些模块是如何工作的。
下面是我尝试读行的代码:
import * as readline from 'readline';
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
interface Person {
firstName: string;
lastName: string;
}
let p: Person = { firstName: '', lastName: '' };
rl.question('Enter your first name: ', (input) => {
p.firstName = input;
});
rl.question('Enter your last name: ', (input) => {
p.lastName = input;
});
rl.close();
console.log(`Hello ${p.firstName} ${p.lastName}!`);
发布于 2019-12-27 17:48:48
JavaScript是一种事件驱动语言,它利用异步回调在IO可用时运行代码。这与许多语言的同步特性形成了鲜明对比,比如C和C++。
在发送输入之前,您的rl.question
回调不会被调用。
你需要重构你的代码来等待这些输入。这里有一种简单的方法可以做到这一点。
import * as readline from 'readline';
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
interface Person {
firstName: string;
lastName: string;
}
let p: Person = { firstName: '', lastName: '' };
rl.question('Enter your first name: ', (input) => {
p.firstName = input;
rl.question('Enter your last name: ', (input) => {
p.lastName = input;
rl.close();
console.log(`Hello ${p.firstName} ${p.lastName}!`);
});
});
https://stackoverflow.com/questions/59504219
复制