简体   繁体   中英

AWS S3 upload not working after converting from callback to Async-Await format using Promisify

I'm using upload method from aws-sdk to upload files to S3 bucket from React app in browser.

The original callback based upload method is as bellow:

var params = {Bucket: 'bucket', Key: 'key', Body: stream};
s3.upload(params, function(err, data) {
  console.log(err, data);
});

I wrapped it with promisify to work it like Async-await as bellow:

const AWS = require('aws-sdk');
const { promisify } = require('es6-promisify');

... <in my React component> ...
async uploadFile() {
try {
    var params = {
      Bucket: <BucketName>,
      Key: <KeyName>,
      Body: <File Stream>
    };
    const res = await uploadToS3Async(params);
    console.log(res);
  } catch (error) {
    console.log(error);
  }
}

Now when I'm calling uploadFile function on some event fired it produces following error:

TypeError: service.getSignatureVersion is not a function
    at ManagedUpload.bindServiceObject  
    at ManagedUpload.configure 
    at new ManagedUpload  
    at upload   
    at new Promise (<anonymous>)

You don't need to use es6-promisify

You can do:

try {
  const params = {Bucket: 'bucket', Key: 'key', Body: stream};  
  const data = await s3.upload(params).promise();
  console.log(data);
}
catch (err) {
  console.log(err);
}

https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/using-promises.html

If you want to make it a Promisify , Then you can simply achieve like this

aws.js

const params = {
    Bucket: 'bucket',
    Key: 'key',
    Body: stream
};

const awsService = {};

awaService.upload = () => {
    return new Promise((resolve, reject) => {
        s3.upload(params, function(err, data) {
            if (err) {
                return reject(err);
            }
            return resolve(data);
        });
    });
};

module.exports = awsService;

On another file just call like this

util.js

const awsService = require('./awsService');

const utils = {};

utils.upload = async () => {
    try {
        const result = await awsService.upload();
        return result;
    } catch (err) {
        console.log(err);
        throw err;
    }
};

module.exports = utils;

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