简体   繁体   English

在执行下一个在 NodeJS 中使用该数据的 function 之前,先完成一个 readln function

[英]Make a readln function finish before executing next function that uses that data in NodeJS

please some help with this.请对此有所帮助。 I want to make a function that creates a nx2 matrix using console inputs (input lines of two spaced integers).我想制作一个 function ,它使用控制台输入(两个间隔整数的输入行)创建一个 nx2 矩阵。 The problem is when I want to make use of this data from another function, my data seems to be undefined.问题是当我想使用来自另一个 function 的数据时,我的数据似乎未定义。 For example, the printmatrix function calls the readfunction but results in undefined because it seems that the readfunc has not yet read all the keystrokes yet, and the printmatrix function is already executed with no input data.例如,printmatrix function 调用 readfunction 但导致 undefined,因为 readfunc 似乎还没有读取所有击键,并且 printmatrix function 已经在没有输入数据的情况下执行。 How I can make sure the function that requires user input finishes before executing the print function or any other function that would require the data to be ready to be read?在执行打印 function 或任何其他 function 之前,我如何确保需要用户输入的 function 完成? Thank you for your help.谢谢您的帮助。

const readline = require('readline');

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

    let arr=[];
    let mat=[];

    rl.on('line', (input) => {
    
    let splitAns=input.split(" ");
    arr.push(splitAns[0])
    arr.push(splitAns[1])
    mat.push(arr)
    arr=[];

  });

  rl.on('close', () =>{
      return (mat)
  })
}

const printmatrix =  () =>{

    const result =  readfunc();
    console.log(result);
}

printmatrix(); // prints undefined :(

I didn't test the code but doing a quickly code review i think that you are missing the result because you're not waiting for it.我没有测试代码,但做了一个快速的代码审查,我认为你错过了结果,因为你没有等待它。 Since the two lines inside printmatrix are executed asynchronous there is no time for readfunc to finish collecting the data into 'mat' variable.由于 printmatrix 中的两行是异步执行的,因此 readfunc 没有时间完成将数据收集到“mat”变量中。

What i suggest is to return a Promise from readsfunc() method and wait for the response before printing it out to console.我建议从 readsfunc() 方法返回 Promise 并等待响应,然后再将其打印到控制台。

So printmatrix will look like this:所以 printmatrix 看起来像这样:

readfunc().then((data) => console.log(data));

More info about Promises -> https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Promise有关 Promises 的更多信息 -> https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Promise

One example from this article:本文的一个例子:

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('foo');
  }, 300);
});

myPromise
  .then(handleResolvedA => console.log(handleResolvedA)

Will print 'foo' after 300 ms将在 300 毫秒后打印 'foo'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM