Reputation: 137
I'm trying to write a lambda function which accepts an image file via web form, and writes it as a new commit to a repository using code commit. For some reason, my lambda function seems to be exiting before the call to createCommit, even though I'm using await in a similar way to my previous calls in the function.
I've tried rewriting the function that wraps createCommit to just use promises, but that doesn't seem to work either. I'm wondering if there is some quirk of lambda that I don't know about or if I'm using async/await incorrectly (I just recently learned how to use them)
this is my main lambda event handler:
exports.handler = async (event) => {
const [file, lastCommitId] = await Promise.all([getFile(event), getLastCommitId()]);
return await createCommit(file, lastCommitId)
.then(result => returnResponse(result, 200))
.catch(err => returnResponse(err, 500));
};
this is my wrapper function for createCommit
async function createCommit(file, parentCommitId) {
const fileContent = await file.content.toString('base64');
const params = {
"authorName": "admin",
branchName,
"commitMessage": "add image",
"email": "n/a",
"parentCommitId": parentCommitId,
"putFiles": [
{
fileContent,
"fileMode": "NORMAL",
"filePath": `src/images/${file.filename}`
}
],
repositoryName
};
console.log("creating commit against last commit id " + parentCommitId);
const result = await codecommit.createCommit(params).promise();
console.log(JSON.stringify(result));
return result;
}
I expect the lambda function to wait until the call to createCommit finished, but it simply prints out the console.log starting with "creating commit against last commit..." and exits.
Upvotes: 2
Views: 13858
Reputation: 137
So it turns out I was using async/await correctly, I just had a 3 second timeout on the lambda function, so it was exiting before it was able to get a response from the createCommit call.
Upvotes: -2
Reputation: 673
You should not use await
and .then
together.
change your code to and trycatch
if you want to catch the exception or failed case.
exports.handler = async (event) => {
const [file, lastCommitId] = await Promise.all([getFile(event), getLastCommitId()]);
return await createCommit(file, lastCommitId);
};
See below example to understand the result in a better way.
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
async function asyncCall() {
console.log('calling');
var result = await resolveAfter2Seconds().then(x=>console.log('inside then ', x));
console.log('after await ',result);
}
asyncCall();
and with out then
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
async function asyncCall() {
console.log('calling');
var result = await resolveAfter2Seconds();
console.log('after await ',result);
}
asyncCall();
Upvotes: 6