javascript - 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.
解决方案
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);
推荐阅读
- java - 使用 SHA-384 签署 ECDSA 时出现“标量不在区间 [1, n - 1] 内”异常
- node.js - 如何在 Node JS 中调试 ssl 日志
- reactjs - 创建反应应用程序 - 如何将 pdf.worker.js 文件从 pdfjs-dist/build 复制到项目的输出文件夹?
- google-apps-script - Googel Apps 脚本测试部署 - “很抱歉,发生服务器错误。请稍候,然后重试。”
- php - 如何在输入类型按钮中有日期选择器值?
- asp.net-core - 本地化适用于数据注释和视图,但不适用于身份页面 ASP.NET Core MVC 3.1
- java - 有没有办法让它更快更通用地做这个问题?
- html - 使用 URL 插入数据
- json - 解析 JSON 返回 EOF
- spring - 如何在不编写主要方法的情况下自启动 Spring 应用程序?