gpt4 book ai didi

javascript - 读取行: read three input line-by-line then loop if true

转载 作者:行者123 更新时间:2023-12-01 01:04:33 24 4
gpt4 key购买 nike

我正在形成一个具有以下结构的输入:

var nodeArray = [
{
position: null,
value: null
},
{
position: null,
value: null
},
// ...
]

逐行读取用户输入。下面列表中的每一行都是 rl.setPrompt(prompt) 中单次迭代的 prompt 参数,

  1. 插入要插入此 Node 的位置>
  2. 插入此 Node 的值>
  3. 您想插入另一个 Node 吗>
    • 如果,则循环...从第 1 步重新开始
    • 如果,则解决promise并关闭rl

根据我对 Node.js 的理解,我能够为这样的简单结构编写代码:

var array = [
value1,
value2,
value3,
//...
]

用户输入形成数组的代码:

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代码的代码:

ma​​in.js

'use strict';

const stdIn = require('input');

const input = stdIn.init([]);

input.then(function fulfilled(response) {
// do something with response
});

我无法扩展 input.js 代码来满足我形成 nodeArray 结构的要求。另外,这段代码有一些小问题,比如它永远不会关闭 rl

最佳答案

在编写异步代码时,您应该始终尝试将尽可能小的任务包装到 Promise 中。在这种情况下,那就是:提示问题,等待答案。由于我们只想听一个答案,因此我们只使用 .once 而不是 .on:

  function prompt(question) {
return new Promise((resolve) => {
rl.setPrompt(question);
rl.prompt();
rl.once("line", resolve);
});
}

既然我们已经做到了,创建 Node 就很简单了:

  async function createNode() {
return {
position: await prompt("Position?"),
value: await prompt("Value?"),
};
}

循环也很简单(如果我们使用 async/await)并且不需要任何递归:

 async function createNodes() {
const result = [];
while(true) {
result.push(await createNode());
if(await prompt("Continue? Yes / No") === "No")
break;
}
return result;
}

关于javascript - 读取行: read three input line-by-line then loop if true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55765231/

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