Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
});
like image 745
Gracie Avatar asked Mar 05 '19 22:03

Gracie


People also ask

Can Lambda upload file to S3?

In this short post, I will show you how to upload file to AWS S3 using AWS Lambda. We will use Python's boto3 library to upload the file to the bucket. Once the file is uploaded to S3, we will generate a pre-signed GET URL and return it to the client.

Is S3 supported by AWS Lambda?

S3 Object Lambda works with your existing applications and uses AWS Lambda functions to automatically process and transform your data as it is being retrieved from S3. The Lambda function is invoked inline with a standard S3 GET request, so you don't need to change your application code.

How do I transfer files from S3 bucket to Lambda?

Add below Bucket Access policy to the IAM Role created in Destination account. Lambda function will assume the Role of Destination IAM Role and copy the S3 object from Source bucket to Destination. In the Lambda console, choose Create a Lambda function. Directly move to configure function.


1 Answers

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

like image 136
Richard Avatar answered Sep 28 '22 06:09

Richard