Write to S3 bucket using Async/Await in AWS Lambda

允我心安 提交于 2021-02-18 21:12:07

问题


I have been using the code below (which I have now added await to) to send files to S3. It has worked fine with my lambda code but as I move to transfer larger files like MP4 I feel I need async/await.

How can I fully convert this to async/await?

exports.handler = async (event, context, callback) => {
...
// Copy data to a variable to enable write to S3 Bucket
var result = response.audioContent;
console.log('Result contents ', result);

// Set S3 bucket details and put MP3 file into S3 bucket from tmp
var s3 = new AWS.S3();
await var params = {
Bucket: 'bucketname',
Key: filename + ".txt",
ACL: 'public-read',
Body: result
};

await s3.putObject(params, function (err, result) {
if (err) console.log('TXT file not sent to S3 - FAILED'); // an error occurred
else console.log('TXT file sent to S3 - SUCCESS');    // successful response
context.succeed('TXT file has been sent to S3');
});

回答1:


You only await functions that return a promise. s3.putObject does not return a promise (similar to most functions that take a callback). It returns a Request object. If you want to use async/await, you need to chain the .promise() method onto the end of your s3.putObject call and remove the callback (https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Request.html#promise-property)

try { // You should always catch your errors when using async/await
  const s3Response = await s3.putObject(params).promise();
  callback(null, s3Response);
} catch (e) {
  console.log(e);
  callback(e);
}



回答2:


As @djheru said, Async/Await only works with functions that return promises. I would recommend creating a simple wrapper function to assist with this problem.

const putObjectWrapper = (params) => {
  return new Promise((resolve, reject) => {
    s3.putObject(params, function (err, result) {
      if(err) resolve(err);
      if(result) resolve(result);
    });
  })
}

Then you could use it like this:

const result = await putObjectWrapper(params);

Here is a really great resource on Promises and Async/Await:

https://javascript.info/async



来源:https://stackoverflow.com/questions/55012396/write-to-s3-bucket-using-async-await-in-aws-lambda

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!