Reputation: 1402
I am using AWS SDK and I am running this code using Lambda. I noticed that when I used upload function with callback inside an async function, it does not execute the function.
const aws = require('aws-sdk');
exports.handler = async (event) => {
const s3 = new aws.S3();
console.log('START UPLOAD')
const params = {
Bucket: 'practice-bucket',
Key: 'hello.txt',
Body: "hello",
}
s3.upload(params, function(err, data) {
console.log(err, data);
});
};
I know how to make this work. Either by changing the function to a non-async function or by using await and turning the response of upload() into a promise. But I am still curious why wouldn't it execute the upload() function? I am expecting it just to execute it just a regular function since I am not telling it to await.
Upvotes: 0
Views: 1035
Reputation: 2321
This is how Javascript's event loop work with async functions in your case the function is returning before s3.upload is complete.
You can fix this issue by converting s3.upload into a promise and then using await to get the result and block the return of your async handler
await result = s3.upload(params).promise();
Upvotes: 1