Search code examples
node.jsasync-awaitaws-lambdaes6-promiseaws-codecommit

How do I ensure a Lambda function waits for call to an async function with await?


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.


Solution

  • 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.