简体   繁体   中英

DeprecationWarning: Calling an asynchronous function without callback is deprecated with AWS JS SDK

I am trying to use Promises and AWS JS SDK For the first time and I am getting the following error

DeprecationWarning: Calling an asynchronous function without callback is deprecated.

I have provided a stack trace below. It appears the error is occurring where I try and use fs.unlink to remove the files I downloaded.

exports.generate = function (req, res) {

    if (typeof Promise === 'undefined') {
      AWS.config.setPromisesDependency(require('bluebird'));
    }

    var removeBatch = function removeBatch(files) {
        return Promise.all(files.map(function(file) {
            return fs.unlink(file.key);
        }));
    };

    var getBatch = function getBatch(files) {
        return Promise.all(files.map(function(file) {
            var params = {
                Bucket: 'my-bucket',
                Key: file.key
            };
            return app.s3.getObject(params).createReadStream().pipe(file.stream);
        }));
    };

    var fileNames = ['Original 106fm Logo #268390.jpg', 'test.jpg'];
    var files = fileNames.map(function(fileName) {
      return {
        key: fileName,
        stream: fs.createWriteStream(fileName)
      };
    });


    getBatch(files)
        .then(removeBatch.bind(null, files))
        .catch(console.error.bind(console));

}

This is the stack trace

(node:63311) [DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated.
at makeCallback (fs.js:127:12)
at Object.fs.unlink (fs.js:1054:14)
at /src/splash.js:12:7
at Array.map (native)
at removeBatch (/src/splash.js:11:28)
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:208:7)

How do I correctly return a Promise from my removeBatch method?

If you want to use a version of fs.unlink that returns a promise instead of taking a callback then use the mz module like this:

const fs = require('mz/fs');

See the docs:

It will not only let you do things like this:

fs.unlink(name)
  .then(() => console.log('Success'))
  .catch(err => console.log('Error:', err));

but also this inside of async functions:

try {
  await fs.unlink(name);
} catch (e) {
  console.log('Error:', e);
}

Now, to your question:

How do I correctly return a Promise from my removeBatch method?

With the mz/fs version of .unlink() it's a one-liner:

const removeBatch = files => Promise.all(files.map(file => fs.unlink(file.key));

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