![](/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.