误导性的“不推荐调用不带回调的异步函数”警告

misleading “Calling an asynchronous function without callback is deprecated” warning

NodeJS 给我一个警告

(node:32600) [DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated.

当我 运行 这个“测试”时:

describe('whatever', () => {
  it('test simple', async () => {
    const dir = './build/fileTests';

    if (fs.existsSync(dir)) {
      console.log(`deleting ${dir}`);
      await fs.rmdir(dir);
    }
  });
});

好吧,我几乎同意,使用没有回调的异步函数是不好的(因为只有在 cb 中你才能确定,它发生了,继续等等......

...如果不是我故意使用ES7 async/await, because they make it synchronous, so I can work with whatever I get... (in this special case, I could evade to rmdirSync,但这不是我的意思...)

所以我的问题:我怎样才能摆脱这些警告?

– 在使用 async/await 时,以一种有意义的方式... – 处理 return 值,如 const r = ... 不被识别为“回调处理”...

fs.rmdir 不是 return promise 对象,这就是此代码因 swag 而失败的原因。你必须承诺它,使用库或 util 核心模块

中的 node.js promisify 方法

注意:如果您对 fs 核心模块中的其他 async 方法使用相同的方法,它将失败

这样做

const util = require("util");
const fs = require("fs");
const removeDir = util.promisify(fs.rmdir);

const rmDir = async () => {
   try {
      await removeDir("directory_name");
   } catch(ex) {
      console.error(ex)
   }
}

只要确保你承诺它

编辑: 按照@bergi

的建议声明了一个变量来保存 uti.promisify(fs.rmdir) 的值

编辑: 使用 try .. catch 块添加错误处理