如何在没有承诺的情况下读取异步函数中的文件?

时间:2017-07-01 21:13:55

标签: javascript file fs read-write

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

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的每个文件。

我仍然得到同样的错误,只能通过评论来缩小问题范围。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:4)

首先:async function返回一个承诺。因此,根据定义,您已经在使用承诺。

其次,没有fs.writeFileAsync。您正在寻找fs.writeFile https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback

借助承诺,利用异步功能的力量

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回调样式转换为promises。在异步函数中,您可以使用await关键字将promise的已解析内容存储到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);
    })
  });
}
相关问题