【问题标题】:How do I read a file in an async function without promises?如何在没有承诺的情况下读取异步函数中的文件?
【发布时间】:2017-12-05 12:50:59
【问题描述】:

我正在尝试在异步函数中读取/写入文件(示例):

async readWrite() {
      // Create a variable representing the path to a .txt
      const file = 'file.txt';

      // Write "test" to the file
      fs.writeFileAsync(file, 'test');
      // Log the contents to console
      console.log(fs.readFileAsync(file));
}

但是每当我运行它时,我总是得到错误:

(node:13480) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot read property 'map' of null

我尝试使用 bluebird,方法是在我的项目目录中使用 npm install bluebird 安装它并添加:

const Bluebird = require('bluebird');
const fs = Bluebird.promisifyAll(require('fs'));

到我的index.js(主)文件,以及添加:

const fs = require('fs');

到我不想使用 fs 的每个文件。

我仍然遇到同样的错误,只能通过注释掉东西来将问题缩小到 fs。

任何帮助将不胜感激。

【问题讨论】:

  • 我做对了吗?你不想使用 Promise,但你使用的是 bluebird?
  • bluebird 是一个 Promise 库。

标签: javascript file fs read-write


【解决方案1】:

首先:asyncfunctions 返回一个承诺。所以根据定义,你已经在使用一个 Promise。

第二,没有fs.writeFileAsync。你在找fs.writeFilehttps://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback

通过 Promise,利用异步函数的强大功能

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

// Promisify the fs.writeFile and fs.readFile
const write = util.promisify(fs.writeFile);
const read = util.promisify(fs.readFile);

async readWrite() {
  // Create a variable representing the path to a .txt
  const file = 'file.txt';

  // Write "test" to the file
  await write(file, 'test');
  // Log the contents to console
  const contents = await read(file, 'utf8');
  console.log(contents);
}

在上面:我们使用util.promisify 将使用函数的nodejs 回调样式转换为promise。在异步函数中,您可以使用 await 关键字将已解析的承诺内容存储到 const/let/var。

延伸阅读材料:https://ponyfoo.com/articles/understanding-javascript-async-await

没有承诺,回调风格

const fs = require('fs');
async readWrite() {
  // Create a variable representing the path to a .txt
  const file = 'file.txt';

  // Write "test" to the file
  fs.writeFile(file, 'test', err => {
    if (!err) fs.readFile(file, 'utf8', (err, contents)=> {
      console.log(contents);
    })
  });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-26
    • 2021-08-10
    • 2016-12-13
    • 1970-01-01
    • 2019-05-25
    • 2019-08-16
    • 1970-01-01
    相关资源
    最近更新 更多