如何使readline在Typescript中的循环内工作?

时间:2019-09-25 10:46:57

标签: typescript

我真的是Typescript的新手。我写了一段代码来做类似C的“ While + scanf”。

以下是我的代码:


class VM:
    def __init__(self, user_id, name, template):
        self.user_id = user_id
        self.name = name
        self.template = template

    @staticmethod
    def from_row(row):
        return VM(row[0], row[1], row[2])

all_vms = []
for row in mycursor:
    all_vms.append(VM.from_row(row))

令我惊讶的是,在我键入任何内容之前,控制台上充斥着“您还想要更多”吗?我四处搜寻,并怀疑与异步相关的东西。但是我仍然不知道如何正确地使这段简单的代码起作用。

1 个答案:

答案 0 :(得分:0)

将代码更改为

import * as readline from 'readline';
import * as process from 'process';
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
let more = 1;
read();

function read() {
    rl.question("Do you want more ", function (answer) {
        if (answer == "no") {
            more = 0;
            console.log("bye");
            rl.close();
        } else {
            more++;
            console.log("next round.." + more);
            read();
        }
    });
}

使用readline-sync

import * as rl from 'readline-sync';
var more = 1;
read();
function read() {
    while (more) {
        let answer = rl.question("Do you want more ");
        if (answer == "no") {
            more = 0;
            console.log("bye");
        } else {
            more++;
            console.log("next round.." + more);
        }
    }
}