node.js - 使用 async/await 逐一读取文件

标签 node.js

代码如下:

function readfile(file) {
   var readline = require('readline');
   var fs = require('fs');
   var fReadAD = fs.createReadStream(file,{ encoding: 'utf8'});
   var objReadlineAD = readline.createInterface({
      input: fReadAD
   });
   objReadlineAD.on('close', (line)=>{
      return new Promise(function(){
          console.log('file:'+file)
      });
   });
}
(async () => {
   await readfile('./import/1.xls')
   await readfile('./import/2.csv')
})();

为什么输出是

file:./import/2.csv
file:./import/1.xls

我觉得应该是

file:./import/1.xls
file:./import/2.csv

我在异步中使用了await。有人能告诉我出了什么问题吗?谢谢!

最佳答案

您的返回 new Promise() 未从 readFile() 返回。因为 Node.js 中的异步操作是非阻塞的,所以 readfile() 函数立即返回(没有返回值),然后文件事件稍后发生(在函数返回之后)。因此,您的 readFile() 函数不会返回任何内容,因此await 无法 promise 实际等待。

这表明您需要一些有关异步事件和操作在 Node.js 中如何工作的基础教育/阅读。

您所做的return new Promise()只是返回到readLine库文件系统事件处理代码并被忽略,因此它不会做任何有用的事情。它实际上并没有返回给任何寻求 promise 的人。

因此,由于您实际上没有返回任何内容,并且实际上没有等待任何内容,因此两个异步操作并行进行,并且不确定哪个操作先完成。这可能取决于每个 readFile() 需要多长时间的详细信息,这只是一场竞赛,看哪一个先完成。你没有控制它们的执行顺序。

事件的顺序是这样的:

  1. 开始第一个readFile()操作。它不返回任何返回值,并且其中的文件操作作为异步代码/事件进行。
  2. 等待未定义,它不会等待任何东西。
  3. 开始第二个readFile()操作。它不返回任何返回值,并且其中的文件操作作为异步代码/事件进行。
  4. 等待未定义,它不会等待任何东西。
  5. 两个 readFile() 操作之一生成其关闭事件(以先完成者为准)。
  6. 其他 readFile() 操作生成其关闭事件。

您可以让 readFile() 实际上返回一个在完成时连接到的 Promise,然后您可以像这样 await :

const fs = require('fs');
const readline = require('readline');

function readfile(file) {
   return new Promise(function(resolve, reject) {
       var fReadAD = fs.createReadStream(file,{ encoding: 'utf8'});
       var objReadlineAD = readline.createInterface({
          input: fReadAD
       });
       objReadlineAD.on('close', () => {
           console.log('file:'+file)
           resolve();
       }).on('error', reject);
   });
}

(async () => {
   await readfile('./import/1.xls')
   await readfile('./import/2.csv')
})();

关于node.js - 使用 async/await 逐一读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50146321/

相关文章:

javascript - 如何使用 Browserify 和 iOS JavaScriptCore

javascript - 如何将数据从 express 传递到我的 hbs View

javascript - Node.js 在包含的 js 文件中快速渲染

node.js - 将选项传递给 Sequelize Hook 不起作用

node.js - 在 VSCode 中调试 CoffeeScript 转到 .js 文件

javascript - Express/NodeJs 中更好的回调 Javascript 代码

node.js - 尝试升级时收到 "must point to an installed version of node"

javascript - NodeJS : myFunction() is not a function

javascript - Node js + Mysql : cannot enqueue because of fatal errors

node.js - Babel 并将 Nodejs 部署到 Google App Engine