小编ros*_*e_x的帖子

Node.js使用async / await读取文件

我正在尝试使用异步/等待代码读取文件。这是我的代码:

var fs = require('fs');

function readFile(fileName) {
  return new Promise(resolve => {
    //console.log(test);
    fs.readFile(fileName, 'utf8', function (err, data) {
      if (err) throw err;

      console.log(fileName)
      console.log(data)
    })
    resolve();
  });
}

async function run() {
  await readFile('file1.txt');
  await readFile('file2.txt');
  readFile('file3.txt');
}

run();
Run Code Online (Sandbox Code Playgroud)

但是结果仍然是随机的。这意味着file3有时会在file2之前读取。我在哪里做错了?

node.js async-await

5
推荐指数
2
解决办法
5267
查看次数

标签 统计

async-await ×1

node.js ×1