如何确保 Lambda 函数等待使用 await 调用异步函数?

Max*_*ane 2 node.js async-await es6-promise aws-lambda aws-codecommit

我正在尝试编写一个 lambda 函数,该函数通过 Web 表单接受图像文件,并使用代码提交将其作为新提交写入存储库。出于某种原因,我的 lambda 函数似乎在调用 createCommit 之前退出,即使我使用 await 的方式与我之前在函数中调用的方式类似。

我尝试重写包装 createCommit 的函数以仅使用承诺,但这似乎也不起作用。我想知道是否有一些我不知道的 lambda 怪癖,或者我是否错误地使用了 async/await(我最近才学会了如何使用它们)

这是我的主要 lambda 事件处理程序:

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));
};
Run Code Online (Sandbox Code Playgroud)

这是我的 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;
}
Run Code Online (Sandbox Code Playgroud)

我希望 lambda 函数等到对 createCommit 的调用完成,但它只是打印出以“针对上次提交创建提交...”开头的 console.log 并退出。

RIC*_*MAR 6

你不应该await.then一起使用。trycatch如果您想捕获异常或失败的情况,请将您的代码更改为。

exports.handler = async (event) => {
   const [file, lastCommitId] = await Promise.all([getFile(event), getLastCommitId()]);

   return await createCommit(file, lastCommitId);
};
Run Code Online (Sandbox Code Playgroud)

请参阅下面的示例以更好地理解结果。

exports.handler = async (event) => {
   const [file, lastCommitId] = await Promise.all([getFile(event), getLastCommitId()]);

   return await createCommit(file, lastCommitId);
};
Run Code Online (Sandbox Code Playgroud)

然后没有

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();
Run Code Online (Sandbox Code Playgroud)