在AWS Lambda中使用Async/Await写入S3存储桶 [英] Write to S3 bucket using Async/Await in AWS Lambda

查看:124
本文介绍了在AWS Lambda中使用Async/Await写入S3存储桶的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用下面的代码(我现在将其添加到其中)将文件发送到S3.它可以很好地与我的lambda代码配合使用,但是当我转移诸如MP4之类的较大文件时,我觉得我需要异步/等待.

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

推荐答案

您只能 await 个返回承诺的函数. s3.putObject 不返回promise(类似于大多数采用回调的函数).它返回一个 Request 对象.如果要使用异步/等待,则需要将 .promise()方法链接到 s3.putObject 调用的末尾,并删除回调( https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Request.html#promise-property )

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

这篇关于在AWS Lambda中使用Async/Await写入S3存储桶的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆