0

编辑:感谢您的回答。我得到了通过 Promises 实现以下目标的解决方案。如果没有它可以以更简单的方式完成,请回答:)

我需要采用如下标准输入

3 60
120 30
100 25
30 10

上面的变量形式

n W
v1 w1
v2 w2
v3 w3
. .
. .
. .
vn wn

v 和 w 值将存储在 v[ ] 和 w[ ] 数组中

我怎样才能使用 rl.on() 来做到这一点?

我的代码如下所示。我不确定在调用问题2时如何传递'n',并且由于我不太清楚的异步行为,代码通常无法按预期工作。在 NodeJS 中的多行输入中获取多个数字的任何最佳实践都会有所帮助。

    var readline = require('readline');
    var rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
        terminal: false
      });
    
      const question1 = () => {
        return new Promise((resolve, reject) => {
          rl.on('line', (line) => {
            const n = line.split(" ")[0];
            const capactity = line.split(" ")[1];
            console.log(n)
            console.log(capactity)
            resolve()
          })
        })
      }
      
      const question2 = n => {
        return new Promise((resolve, reject) => {
        for(var i=0; i<n; i++){
            rl.on('line', (line) => {        
                values.push(line.split(" ")[0]);
                weights.push(line.split(" ")[1]);
                console.log(values);
                console.log(weights);
                resolve()
            })
        }
          
        })
      }
      
      const main = async () => {
        await question1()
        await question2()
        rl.close()
      }
      
      main()
4

1 回答 1

0

您需要返回所需的值question1并将它们作为参数传递给question2

我也会尝试在使用时摆脱任何回调模式async-await,所以改变

new Promise((resolve) => {
  rl.on('line', (line) => {
    // calculate
    resolve();
  })
})

const line = await new Promise(resolve => rl.on('line', resolve));
// calculate

见下文:

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    terminal: false
});

const question1 = async () => {
    const line = await new Promise(resolve => rl.on('line', resolve)); 
    const n = line.split(" ")[0];
    const capactity = line.split(" ")[1];
    return { n, capactity };
}

const question2 = async (n) => {
    const values = [];
    const weights = [];
    for(let i = 0; i < n; i++) {
        const line = await new Promise(resolve => rl.on('line', resolve)); 
        values.push(line.split(" ")[0]);
        weights.push(line.split(" ")[1]);
    }

    return { values, weights };
}

const main = async () => {
    const { n, capactity } =  await question1();
    const { weights, values } = await question2(n);
    rl.close();
    console.log(weights, values);
}

main();
于 2020-12-01T13:41:55.877 回答