gpt4 book ai didi

readline 对象的 Javascript 范围

转载 作者:行者123 更新时间:2023-12-03 02:43:19 25 4
gpt4 key购买 nike

困惑为什么此代码在第二个提示后挂起:

var readline = require('readline');

var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});

function curry () {
let inputs = []
function _curry() {
if (inputs.length > 5) {
for (var i = 0; i < inputs.length; i++) {
console.log(inputs[i]);
}
} else {
rl.question("Number?", function(answer) {
inputs.push(answer)
rl.close();
_curry()
});
}
}
_curry()
}

curry()

===>

~/Desktop$ node curry.js

Number?1

Number?2

HANG

但是,这个:

var readline = require('readline');

function curry () {
let inputs = []
function _curry() {
if (inputs.length > 5) {
for (var i = 0; i < inputs.length; i++) {
console.log(inputs[i]);
}
} else {
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("Number?", function(answer) {
inputs.push(answer)
rl.close();
_curry()
});
}
}
_curry()
}

curry()

工作正常:

数字?12号数量?3数量?4数量?5数量?6123456

这似乎是一个范围界定问题?阅读线没有关闭?吊装?

最佳答案

不,这与范围或声明提升无关。只是您太早关闭了 readline 实例(但它似乎是异步的,因此仍然显示第二个提示)。你应该使用

function curry () {
// better don't use a global, especially if you don't leave it open
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let inputs = []
function _curry() {
if (inputs.length > 5) {
rl.close(); // close it only once you're done with *everything*
for (var i = 0; i < inputs.length; i++) {
console.log(inputs[i]);
}
} else {
rl.question("Number?", function(answer) {
inputs.push(answer)
_curry()
});
}
}
_curry()
}

关于readline 对象的 Javascript 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48217613/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com