【问题标题】:Write to S3 bucket using Async/Await in AWS Lambda在 AWS Lambda 中使用 Async/Await 写入 S3 存储桶
【发布时间】:2019-07-27 11:40:27
【问题描述】:

我一直在使用下面的代码(我现在添加了等待)将文件发送到 S3。它在我的 lambda 代码上运行良好,但当我转移到 MP4 等较大的文件时,我觉得我需要 async/await。

如何将其完全转换为 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 var params = ... await 只对promise有用

标签: javascript node.js amazon-s3 async-await aws-lambda


【解决方案1】:

你只有 await 返回一个承诺的函数。 s3.putObject 不返回承诺(类似于大多数接受回调的函数)。它返回一个Request 对象。如果要使用 async/await,则需要将 .promise() 方法链接到 s3.putObject 调用的末尾并删除回调 (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);
}

【讨论】:

  • 我认为这是正确的,但您可能也不想在这里使用已弃用的context.succeed(),因为它混合了异步/等待和回调。返回响应或承诺,因为您在异步函数(处理程序)中,是吗?
  • 在 async/await 情况下应该用什么替换 context.succeed(s3Response);
  • 或许callback(null, s3Response);?
  • 是的,我不确定context.succeed。我做了一点研究,上下文对象实际上只是为了提供有关 lambda 请求的附加信息(docs.aws.amazon.com/lambda/latest/dg/…)。而不是context.succeed,你想调用callback(null, s3Response)。我会更新我的答案
【解决方案2】:

正如@djheru 所说,Async/Await 仅适用于返回承诺的函数。 我建议创建一个简单的包装函数来帮助解决这个问题。

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

那么你可以这样使用它:

const result = await putObjectWrapper(params);

这是关于 Promises 和 Async/Await 的非常棒的资源:

https://javascript.info/async

【讨论】:

  • 我想 if(err) resolve(err);应该替换为 if(err) reject(err);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-28
  • 2015-03-21
  • 1970-01-01
  • 1970-01-01
  • 2019-12-11
  • 1970-01-01
  • 2017-12-25
相关资源
最近更新 更多