简体   繁体   中英

Write to S3 bucket using Async/Await in AWS Lambda

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

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

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

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