首页 > 解决方案 > How to make a function to wait for an async function to resolve in node js?

问题描述

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.

标签: javascriptnode.js

解决方案


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);

推荐阅读