![](/img/trans.png)
[英]AWS S3 upload not working after converting from callback to Async-Await format using Promisify
[英]Write to S3 bucket using Async/Await in AWS Lambda
我一直在使用下面的代码(我现在已经添加了等待)将文件发送到 S3。 它在我的 lambda 代码上运行良好,但是当我开始传输像 MP4 这样的更大文件时,我觉得我需要异步/等待。
如何将其完全转换为异步/等待?
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
不返回承诺(类似于大多数采用回调的函数)。 它返回一个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);
}
正如@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 的非常棒的资源:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.