【问题标题】:Read file asynchronously [duplicate]异步读取文件[重复]
【发布时间】:2021-08-07 18:57:12
【问题描述】:

我正在尝试使用fs.readFile() 读取文件,然后在下面的代码中使用结果。读取过程必须是异步的。这是我目前所拥有的:

var file = async () => {
  await fs.readFile(__dirname + "/file.json", "utf-8", (err, data) => {
    if (err) throw err
    return JSON.parse(data)
  })
}
console.log(file());

由于某种原因,此代码始终记录 undefined。有什么方法可以在不移动readFile 回调中的console.log 语句的情况下做到这一点?

【问题讨论】:

  • file 变量上方的代码中是一个函数。具体来说就是函数async () ...。你的代码类似于写async function file () { ... }。也就是说,file 是函数的名称
  • 那么async 应该去哪里?因为即使console.log(file()) 也不起作用。
  • async 关键字只是让函数返回一个 Promise。所以你的 file 函数会返回一个 Promise。
  • 哦,好的。那么如何异步获取文件数据呢?
  • 你应该在记录之前等待结果, const result = await file();控制台日志(结果)

标签: node.js


【解决方案1】:

值得注意的修改: fs.promises.readFile => 如果您不使用承诺,请不要使用等待。 如果你确实使用了 Promise => 不要使用回调。

async function readFile() {
  const data = await fs.promises.readFile(__dirname + "/file.json", "utf-8");
  return JSON.parse(data)
}

(async() => {
  console.log(await readFile());
})();

对于同步版本,请参阅其他 cmets。 (但出于性能原因,我更喜欢异步)

【讨论】:

    【解决方案2】:

    使用承诺

    const someFunction = async () => {
        try {
            var file = () => {
                return new Promise((resolve, reject) => {
                    fs.readFile(__dirname + "/file.json", "utf-8", (err, data) => {
                        if (err) reject(err)
                        else resolve(data)
                    })
                })
                
            }
            console.log(await file()); // this is the key
        } catch (err) {
            console.log(err)
        }
    }
    

    您需要添加一个try-catch 块来捕获reject 承诺或引发的任何错误。这样就更好了。

    或旧的函数样式

    async function someFunction() {
        // the contents are the same
        // ...
    }
    

    问题是,file() 异步运行,代码没有等待结果。将await 放在fs.readFile() 函数上并不意味着等待file() 变量完成其执行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-20
      • 2019-01-13
      • 2012-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多