1

I am new to node js and I have never worked with promises before so I would greatly appreciate any advice. I am using an async await function to read a .txt file line by line, it returns an array.

async function processLineByLine() {
  const fileStream = fs.createReadStream('input.txt');
  const array = [];
  const rl = readline.createInterface({
    input: fileStream,
    crlfDelay: Infinity
  });

  for await (const line of rl) {
    array.push(line)
  }

  return array
}

I want to create a new instance of a class using this array as an argument, like this:

let variableName = new ClassName(array)

So that I can call functions on this instance of an object and manipulate its state. I have tried to do this:

async function input() {
  var result = await processLineByLine();
  return result
}

let variableName = ClassName(input())
variableName.someFunction()

But it fails as the state I am trying to access is undefined and console.log(input()) shows promise pending.

Edzeno
  • 13
  • 2
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – ASDFGerte Dec 15 '19 at 12:20

1 Answers1

1

You need to put all the code after the await:

async function input() {
  var result = await processLineByLine();
  let variableName = ClassName(result)
  variableName.someFunction();
}

input().catch(console.error);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375