我正在形成具有以下结构的输入:
var nodeArray = [
{
position: null,
value: null
},
{
position: null,
value: null
},
// ...
]
逐行读取用户输入。下表中的每一行都是prompt
中的rl.setPrompt(prompt)
自变量,用于单次迭代,
Yes
,循环... 从步骤1重新开始 No
,请解决promise
并关闭rl
。根据对node.js的了解,我能够为这样的简单结构编写代码:
var array = [
value1,
value2,
value3,
//...
]
用户输入以形成array
的代码:
input.js
'use strict';
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
module.exports = {
init : async function(arr) {
this.arr = arr;
const pr = await this.userInputOn();
return pr;
},
promptUpdater : function() {
rl.setPrompt(`Insert ${this.arr.length}th array Element> `);
rl.prompt();
},
userInputOn : function() {
return new Promise((resolve, reject) => {
this.promptUpdater();
rl.on('line', (line) => {
if(line === "close") resolve(this.arr);
else {
this.arr.push(+line);
this.promptUpdater();
}
});
});
},
}
使用 input.js 代码的代码:
main.js
'use strict';
const stdIn = require('input');
const input = stdIn.init([]);
input.then(function fulfilled(response) {
// do something with response
});
我无法扩展input.js
代码以满足我对形成nodeArray
结构的要求。另外,此代码有一些故障,例如,它永远不会关闭rl
。
答案 0 :(得分:2)
编写异步代码时,应始终尝试将尽可能小的任务包装到Promise中。在这种情况下,将是:提示问题,等待答案。因为我们只想听一个答案,所以我们只使用.once
而不是.on
:
function prompt(question) {
return new Promise((resolve) => {
rl.setPrompt(question);
rl.prompt();
rl.once("line", resolve);
});
}
现在我们已经有了,创建一个节点很简单:
async function createNode() {
return {
position: await prompt("Position?"),
value: await prompt("Value?"),
};
}
循环也很简单(如果我们使用异步/等待),并且不需要任何递归:
async function createNodes() {
const result = [];
while(true) {
result.push(await createNode());
if(await prompt("Continue? Yes / No") === "No")
break;
}
return result;
}