确认此代码在第二次提示后挂起的原因:
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()
===&GT;
〜/ Desktop $ node curry.js
数α1
数?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()
工作正常:
数?1 2号 号码?3 数?4 数≤5 号码?6 1 2 3 4 五 6
这似乎在某种程度上是一个范围问题? readline没有关闭?起重?
答案 0 :(得分:1)
不,这与范围或声明吊装无关。只是你过早地关闭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()
}
答案 1 :(得分:0)
我注意到我的原始帖子并不是一个严格的currying示例,但是它的目的是为了产生类似的功能,更加坚固,例如:
function curry(length) {
let inputs = []
function _curry(input) {
inputs.push(input)
if (inputs.length === length) {
for (var i = 0; i < inputs.length; i++) {
console.log(inputs[i]);
}
} else {
return _curry
}
}
return _curry
}
curry(4)(1)(2)(3)(4)