await 是不是在等待从文件中读取数据?

Await is not waiting to read data from file?

我写了下面的代码来从文件中读取数据并推入数组。但是 attachments.length 是先打印 0,然后加载数据并打印。

const fs=require('fs');
const util=require('util');
const files=['t1.csv','t2.csv','t3.csv'];
async getdata(){
     const read=util.promisify(fs.readFile);
     let attachments = [];
     async function run(file){
         let data=await read(file);
         attachments.push(data);
     } 
     for(let file of files){
         await run(file);
     }
     console.log(attachments.length);//should print 3
}

如何先加载数据再正确推送

编辑: 更改部分代码以使用 await。但是在第一次迭代后循环中断而没有给出任何错误也不打印我的 attchments.length .

编辑 2: 问题已解决。调用函数也应该需要等待。谢谢大家。

发生这种情况是因为在这种情况下也应该等待 run(), 见 async function

一种方法是使用 IIFE:

(async file => {
    let data = await read(file);
    console.log(data);
    attachments.push(data);
})('/home/nadeem/Desktop/test.csv')

当您调用 async 函数时,它 returns 承诺最终将使用函数返回的值解析(或者拒绝并从函数内部抛出未捕获的异常)。

所以您试图在 run () 函数完成之前记录附件数。这是您需要的:

run('/home/nadeem/Desktop/test.csv')
  .then(() => console.log(attachments.length))