简体   繁体   中英

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

NodeJS gives me a warning

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

when I run this 'test':

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

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

Well, I would almost agree, that using async-functions without a callback is bad (since only within the cb you can know for sure, it happened, go on, etc...

... if it wasn't for my intentional use of the 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 , but that's not my point...)

so my Question: How can I get rid of warnings like these?

– in a meaningful way, when working with async/await... – dealing with the return value, as in const r = ... is not recognized as 'callback handling'...

fs.rmdir does not return a promise object, that's why this code fails with swag. You have to promisify it , using a library or the node.js promisify method in util core module

Note: if you use this same approach for other async methods in the fs core module, it will fail

do this

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)
   }
}

Just make sure you promisify it

Edit: declared a variable to hold the value of uti.promisify(fs.rmdir) as suggested by @bergi

Edit: Add error handling with try .. catch block

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM