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

Javascript 如何在没有承诺的情况下读取异步函数中的文件?,javascript,file,fs,read-write,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 c

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

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安装bluebird并添加:

const Bluebird = require('bluebird');
const fs = Bluebird.promisifyAll(require('fs'));
添加到my index.js主文件,以及添加:

const fs = require('fs');
到每个我不想使用fs的文件

我仍然会犯同样的错误,只能通过注释内容将问题缩小到fs

任何帮助都将不胜感激。

首先:异步函数返回一个承诺。因此,根据定义,您已经在使用承诺

其次,没有fs.writeFileAsync。您正在寻找fs.writeFile

通过承诺,利用异步函数的强大功能 在上文中:我们使用函数将nodejs回调风格转变为承诺。在异步函数中,可以使用关键字将承诺的解析内容存储到const/let/var

进一步阅读材料:

没有承诺,回访式 首先:异步函数返回一个承诺。因此,根据定义,您已经在使用承诺

其次,没有fs.writeFileAsync。您正在寻找fs.writeFile

通过承诺,利用异步函数的强大功能 在上文中:我们使用函数将nodejs回调风格转变为承诺。在异步函数中,可以使用关键字将承诺的解析内容存储到const/let/var

进一步阅读材料:

没有承诺,回访式
我说得对吗?你不想用承诺,但你用的是蓝鸟?蓝鸟是承诺库。我说得对吗?你不想使用承诺,但你在使用蓝鸟?蓝鸟是一个承诺库。
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);
}
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);
    })
  });
}