【问题标题】:DeprecationWarning: Calling an asynchronous function without callback is deprecated with AWS JS SDKDeprecationWarning:不推荐使用 AWS JS SDK 调用不带回调的异步函数
【发布时间】:2023-04-10 20:02:01
【问题描述】:

我第一次尝试使用 Promises 和 AWS JS SDK,但出现以下错误

DeprecationWarning:不推荐调用不带回调的异步函数。

我在下面提供了堆栈跟踪。在我尝试使用fs.unlink 删除我下载的文件时,似乎发生了错误。

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

}

这是堆栈跟踪

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

如何从我的 removeBatch 方法中正确返回 Promise?

【问题讨论】:

    标签: javascript node.js amazon-web-services


    【解决方案1】:

    如果您想使用返回 Promise 而不是回调的 fs.unlink 版本,请使用 mz 模块,如下所示:

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

    查看文档:

    它不仅可以让你做这样的事情:

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

    还有async函数内部的这个:

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

    现在,回答你的问题:

    如何从我的 removeBatch 方法中正确返回 Promise?

    mz/fs 版本的 .unlink() 是单行的:

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

    【讨论】:

      猜你喜欢
      • 2018-01-09
      • 2018-04-11
      • 2017-05-02
      • 2017-08-27
      • 1970-01-01
      • 2019-05-09
      • 2018-03-27
      • 2015-09-08
      • 2019-01-07
      相关资源
      最近更新 更多